This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Converts Generic List to DataTable | |
public DataTable ToDataTable<T>(List<T> items) | |
{ | |
DataTable dataTable = new DataTable(typeof(T).Name); | |
//Get all the properties by using reflection | |
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); | |
foreach (PropertyInfo prop in Props) | |
{ | |
//Setting column names as Property names | |
dataTable.Columns.Add(prop.Name); | |
} | |
foreach (T item in items) | |
{ | |
var values = new object[Props.Length]; | |
for (int i = 0; i < Props.Length; i++) | |
{ | |
values[i] = Props[i].GetValue(item, null); | |
} | |
dataTable.Rows.Add(values); | |
} | |
return dataTable; | |
} | |
// Usage | |
DataTable dt = new DataTable(); | |
dt = ToDataTable<Employee>(data); |
Comments
Post a Comment