Skip to content

Instantly share code, notes, and snippets.

@stephenkirk
Created April 16, 2019 13:36
Show Gist options
  • Save stephenkirk/81b4e5fe0a3cd9026d29ec1fd24bf8f7 to your computer and use it in GitHub Desktop.
Save stephenkirk/81b4e5fe0a3cd9026d29ec1fd24bf8f7 to your computer and use it in GitHub Desktop.
public static class DataTableExtensions
{
public static DataTable ToDataTable<T>(this IEnumerable<T> data)
{
var properties = TypeDescriptor.GetProperties(typeof(T));
var table = new DataTable();
foreach (PropertyDescriptor prop in properties)
{
var name = prop.Name;
var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
table.Columns.Add(name, type);
}
foreach (var item in data)
{
var row = table.NewRow();
foreach (PropertyDescriptor prop in properties) row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment