Convert Datatable to Collection using Generic





5.00/5 (3 votes)
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(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<string,> dic)
{
List lst = new System.Collections.Generic.List();
Type classType = typeof(T);
PropertyInfo[] propertyInfoList = classType.GetProperties();
List columnsList = table.Columns.Cast().ToList();
T t;
foreach (DataRow item in table.Rows)
{
t = (T)Activator.CreateInstance(classType);
foreach (PropertyInfo oneInfo in propertyInfoList)
{
try
{
DataColumn d = columnsList.Find(col => col.ColumnName == dic[oneInfo.Name]);
if (d != null) oneInfo.SetValue(t, item[dic[oneInfo.Name]], null);
}
catch
{
}
}
lst.Add(t);
}
return lst;
}
Class
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
DataTable
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;
dt.Rows.Add(dr);
}
return dt;
}
Convertion
DataTable table = getTable();
Dictionary<string,> dic = new Dictionary<string,>();
dic.Add("FirstName", "FIRST_NAME");
dic.Add("LastName", "LAST_NAME");
List lst = table.ToCollection(dic);