Skip to content

Instantly share code, notes, and snippets.

@rickdailey
Created January 29, 2014 00:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rickdailey/8679306 to your computer and use it in GitHub Desktop.
Save rickdailey/8679306 to your computer and use it in GitHub Desktop.
public static DataTable ToDataTable<TKey, T>(this IEnumerable<IGrouping<TKey, T>> data, string keyName = "Key")
{
var properties = TypeDescriptor.GetProperties(typeof(T));
var table = new DataTable();
table.Columns.Add(keyName, GetRealType(typeof(TKey)));
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, GetRealType(prop.PropertyType));
foreach (IGrouping<TKey, T> group in data)
{
foreach (T item in group.Items)
{
DataRow row = table.NewRow();
row[keyName] = group.Key ?? DBNull.Value;
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
}
return table;
}
private static Type GetRealType(Type t)
{
return Nullable.GetUnderlyingType(t) ?? t;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment