Created
January 29, 2014 00:21
-
-
Save rickdailey/8679306 to your computer and use it in GitHub Desktop.
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
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