I\'ve just learned about Generics and I\'m wondering whether I can use it to dynamically build datatables from my classes.
Or I might be missing the point here. Here
Here is a more compact version of David's answer that is also an extension function. I've posted the code in a C# project on Github.
public static class Extensions
{
public static DataTable ToDataTable(this IEnumerable self)
{
var properties = typeof(T).GetProperties();
var dataTable = new DataTable();
foreach (var info in properties)
dataTable.Columns.Add(info.Name, Nullable.GetUnderlyingType(info.PropertyType)
?? info.PropertyType);
foreach (var entity in self)
dataTable.Rows.Add(properties.Select(p => p.GetValue(entity)).ToArray());
return dataTable;
}
}
I have found that this works very well in conjunction with code to write a DataTable to CSV.