Created
April 16, 2019 13:36
-
-
Save stephenkirk/81b4e5fe0a3cd9026d29ec1fd24bf8f7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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