Home » csharp » Convert DataTable to Generic List

Convert DataTable to Generic List

This helper class is usefull to convert DataTable to List of any Type(generic) in c#.

 public static class Helper<br />
    {<br />
        /// &lt;summary&gt;<br />
        /// Converts a DataTable to a list with generic objects<br />
        /// &lt;/summary&gt;<br />
        /// &lt;typeparam name=&quot;T&quot;&gt;Generic object&lt;/typeparam&gt;<br />
        /// &lt;param name=&quot;table&quot;&gt;DataTable&lt;/param&gt;<br />
        /// &lt;returns&gt;List with generic objects&lt;/returns&gt;<br />
        public static List&lt;T&gt; DataTableToList&lt;T&gt;(this DataTable table) where T : class, new()<br />
        {<br />
            try<br />
            {<br />
                List&lt;T&gt; list = new List&lt;T&gt;();</p>
<p>                foreach (var row in table.AsEnumerable())<br />
                {<br />
                    T obj = new T();</p>
<p>                    foreach (var prop in obj.GetType().GetProperties())<br />
                    {<br />
                        try<br />
                        {<br />
                            PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);<br />
                            propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);<br />
                        }<br />
                        catch<br />
                        {<br />
                            continue;<br />
                        }<br />
                    }</p>
<p>                    list.Add(obj);<br />
                }</p>
<p>                return list;<br />
            }<br />
            catch<br />
            {<br />
                return null;<br />
            }<br />
        }<br />
    }

Leave a Reply

Subscribe

Join 901 other subscribers