Saturday, November 7, 2015

Convert datatable to List collection in C#.net


public static List<T> ToCollection<T>( DataTable dt)
{
List<T> lst = new System.Collections.Generic.List<T>();
Type tClass = typeof(T);
PropertyInfo[] pClass = tClass.GetProperties();
List<DataColumn> dc = new 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;
}

No comments:

Post a Comment