65.9K
CodeProject is changing. Read more.
Home

Convert Datatable to Collection using Generic

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.96/5 (20 votes)

May 13, 2011

CPOL
viewsIcon

106525

This is an example to Convert from a datatable to a specific type of collection using Generic

Prerequisite: using System.Reflection; Sometime at the time of coding, we need to convert a DataTable to a generic list. Suppose I have a DataTable which contains Employee information. Now if I want to convert this into the collection of the Employee class. For this type of requirement, there is no in-built function. We need to write our own coding. And after sometime, we got the same requirement to some other type of object, then again new coding for that specific type. Instead, we can make our custom method which will work for all types of Class. First, I am creating an Extension Method.
public static class MyExtensionClass
{
     public static List<T> ToCollection<T>(this DataTable dt)
    {
        List<T> lst = new System.Collections.Generic.List<T>();
        Type tClass = typeof(T);
        PropertyInfo[] pClass = tClass.GetProperties();
        List<DataColumn> dc = dt.Columns.Cast<DataColumn>().ToList();
        T cn;
        foreach (DataRow item in dt.Rows)
        {
            cn = (T)Activator.CreateInstance(tClass);
            foreach (PropertyInfo pc in pClass)
            {
                // Can comment try catch block. 
                try
                {
                    DataColumn d = dc.Find(c => c.ColumnName == pc.Name);
                    if (d != null)
                        pc.SetValue(cn, item[pc.Name], null);
                }
                catch
                {
                }
            }
            lst.Add(cn);
        }
        return lst;
    }
}
We can comment line 1 and line 2, still it will work because of the try block. Here is an example.

Class

    public class ClassName
    {
        public string ItemCode { get; set; }
        public string Cost { get; set; }
        public override string ToString()
        {
            return "ItemCode : " + ItemCode + ", Cost : " + Cost;
        }
    }

DataTable

    public DataTable getTable()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add(new DataColumn("ItemCode", typeof(string)));
        dt.Columns.Add(new DataColumn("Cost", typeof(string)));
        DataRow dr;
        for (int i = 0; i < 10; i++)
        {
            dr = dt.NewRow();
            dr[0] = "ItemCode" + (i + 1);
            dr[1] = "Cost" + (i + 1);
            dt.Rows.Add(dr);
        }
        return dt;
    }
Now we can convert this DataTable to List like that:
    DataTable dt = getTable();
    List<ClassName> lst = dt.ToCollection<ClassName>();
    foreach (ClassName cn in lst)
    {
        Response.Write(cn.ToString() + "<BR/>");
    }