How to convert generic list (List<t>) into datatable
public static System.Data.DataTable ListToDataTable<T>(List<T> list)
{
DataTable table = new DataTable();
foreach (System.Reflection.PropertyInfo info in typeof(T).GetProperties())
{
table.Columns.Add(new DataColumn(info.Name, info.PropertyType));
}
foreach (T t in list)
{
DataRow row = table.NewRow();
foreach (System.Reflection.PropertyInfo info in typeof(T).GetProperties())
{
row[info.Name] = info.GetValue(t, null);
}
table.Rows.Add(row);
}
return table;
}
{
DataTable table = new DataTable();
foreach (System.Reflection.PropertyInfo info in typeof(T).GetProperties())
{
table.Columns.Add(new DataColumn(info.Name, info.PropertyType));
}
foreach (T t in list)
{
DataRow row = table.NewRow();
foreach (System.Reflection.PropertyInfo info in typeof(T).GetProperties())
{
row[info.Name] = info.GetValue(t, null);
}
table.Rows.Add(row);
}
return table;
}
No comments:
Post a Comment