I have the following extension, which generates a DataTable
from an IEnumerable
:
public static DataTable AsDataTable<T>(this IEnumerable<T> enumerable)
{
DataTable table = new DataTable();
T first = enumerable.FirstOrDefault();
if (first == null)
return table;
PropertyInfo[] properties = first.GetType().GetProperties();
foreach (PropertyInfo pi in properties)
table.Columns.Add(pi.Name, pi.PropertyType);
foreach (T t in enumerable)
{
DataRow row = table.NewRow();
foreach (PropertyInfo pi in properties)
row[pi.Name] = t.GetType().InvokeMember(pi.Name, BindingFlags.GetProperty, null, t, null);
table.Rows.Add(row);
}
return table;
}
However, on huge amounts of data, the performance isn't very good. Is there any obvious performance fixes that I'm unable to see?