Click here to Skip to main content
13,289,626 members (59,315 online)
Click here to Skip to main content
Add your own
alternative version


2 bookmarked
Posted 12 Aug 2011

Convert Datatable to Collection using Generic

, 13 Aug 2011
Rate this:
Please Sign up or sign in to vote.
Very nice!I've modified ToCollection(this DataTable dt) extension function, so if DataTable column names and class property names are different, then you can use this alternative:public static List ToCollection(this DataTable table, Dictionary dic){ List lst = new...
Very nice!

I've modified ToCollection<t>(this DataTable dt)</t> extension function, so if DataTable column names and class property names are different, then you can use this alternative:

public static List<t> ToCollection<t>(this DataTable table, Dictionary<string,> dic)
    List<t> lst = new System.Collections.Generic.List<t>();
    Type classType = typeof(T);
    PropertyInfo[] propertyInfoList = classType.GetProperties();
    List<datacolumn> columnsList = table.Columns.Cast<datacolumn>().ToList();
    T t;
    foreach (DataRow item in table.Rows)
        t = (T)Activator.CreateInstance(classType);
        foreach (PropertyInfo oneInfo in propertyInfoList)
                DataColumn d = columnsList.Find(col => col.ColumnName == dic[oneInfo.Name]);
                if (d != null) oneInfo.SetValue(t, item[dic[oneInfo.Name]], null);
    return lst;


public class Person
    public string FirstName { get; set; }
    public string LastName { get; set; }


public DataTable getTable()
    DataTable dt = new DataTable();
    dt.Columns.Add(new DataColumn("FIRST_NAME", typeof(string)));
    dt.Columns.Add(new DataColumn("LAST_NAME", typeof(string))); 
    DataRow dr;
    for (int i = 1; i < 11; i++)
        dr = dt.NewRow();
        dr["FIRST_NAME"] = "First Name" + i;
        dr["LAST_NAME"] = "Last Name" + i;
    return dt;


DataTable table = getTable();
Dictionary<string,> dic = new Dictionary<string,>();
dic.Add("FirstName", "FIRST_NAME");
dic.Add("LastName", "LAST_NAME"); 
List<person> lst = table.ToCollection<person>(dic);</person></person>


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


About the Author

Vano Maisuradze
Georgia Georgia
No Biography provided

You may also be interested in...


Comments and Discussions

GeneralReason for my vote of 5 I really liked it!! Pin
Anurag Gandhi23-Aug-11 3:07
memberAnurag Gandhi23-Aug-11 3:07 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171207.1 | Last Updated 13 Aug 2011
Article Copyright 2011 by Vano Maisuradze
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid