Click here to Skip to main content
15,886,795 members
Articles / Web Development / ASP.NET
Tip/Trick

Convert Datatable to Collection using Generic

Rate me:
Please Sign up or sign in to vote.
4.96/5 (20 votes)
12 Jun 2011CPOL 104.2K   31   15
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<classname></classname> like that:

DataTable dt = getTable();
List<ClassName> lst = dt.ToCollection<ClassName>();
foreach (ClassName cn in lst)
{
    Response.Write(cn.ToString() + "<BR/>");
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionConverting Dataset to Generic LIst<T> Pin
Jerin Kurian3-Dec-14 18:21
Jerin Kurian3-Dec-14 18:21 
GeneralMy vote of 5 Pin
M Rayhan8-Nov-13 0:18
M Rayhan8-Nov-13 0:18 
QuestionThere is a generic method to do so... Pin
Asad Ali Malik2-Jan-13 20:04
Asad Ali Malik2-Jan-13 20:04 
GeneralMy vote of 5 Pin
Pravin Patil, Mumbai8-Jul-12 22:31
Pravin Patil, Mumbai8-Jul-12 22:31 
GeneralReason for my vote of 5 A great time saver Pin
richardw4823-Aug-11 21:14
richardw4823-Aug-11 21:14 
GeneralRe: thanks Williams Pin
nit_singh26-Aug-11 21:35
nit_singh26-Aug-11 21:35 
GeneralYou can avoid the Activator.CreateInstance call by adding a ... Pin
Richard Deeming23-Aug-11 8:30
mveRichard Deeming23-Aug-11 8:30 
GeneralRe: yes right..i will modify it Pin
nit_singh26-Aug-11 21:36
nit_singh26-Aug-11 21:36 
GeneralRe: You can avoid the Activator.CreateInstance call by adding a ... Pin
Surendra Adhikari SA28-Jul-13 1:42
professionalSurendra Adhikari SA28-Jul-13 1:42 
GeneralDoes your method handle DBNull.Value for all the datatypes. Pin
Mycroft Holmes14-Aug-11 19:59
professionalMycroft Holmes14-Aug-11 19:59 
GeneralRe: yes it handles Pin
nit_singh17-Aug-11 8:10
nit_singh17-Aug-11 8:10 
Generalusefull in some cases.But there may be some performance issu... Pin
leopard44713-Jun-11 19:44
leopard44713-Jun-11 19:44 
GeneralRe: leopard447 - if you have any other suggetion then publicsh h... Pin
nit_singh14-Jun-11 23:58
nit_singh14-Jun-11 23:58 
GeneralRe: Nice article. @leopard447 I was also going to test the code'... Pin
Mutahar15-Jun-11 3:29
Mutahar15-Jun-11 3:29 
Generalgood one Pin
Shahriar Iqbal Chowdhury/Galib16-May-11 11:41
professionalShahriar Iqbal Chowdhury/Galib16-May-11 11:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.