Created
February 16, 2016 06:52
-
-
Save Jtorrecilla/90db81d28bd6be991c6c 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 IEnumerableExtensions | |
| { | |
| public static DataTable ConvertToDataTable<T>(this IEnumerable<T> rows, Func<PropertyInfo, bool> filter) | |
| { | |
| var type = typeof(T); | |
| if (type is DataRow) return rows.ConvertToDataTable(); | |
| var properties = filter == null? type.GetProperties().ToList() : type.GetProperties().Where(filter).ToList(); | |
| var table = BuildTable(type, properties); | |
| CreateRows(table, properties, rows); | |
| return table; | |
| } | |
| internal static DataTable BuildTable(Type type, List<PropertyInfo> properties) | |
| { | |
| var table = new DataTable(); | |
| properties.ForEach(prop => table.Columns.Add(prop.Name)); | |
| return table; | |
| } | |
| internal static void CreateRows<T>(DataTable table, List<PropertyInfo> properties,IEnumerable<T> rows) | |
| { | |
| foreach (var row in rows) | |
| { | |
| var tableRow = table.NewRow(); | |
| foreach (var column in table.Columns) | |
| { | |
| properties.ForEach(property => tableRow[property.Name] = property.GetValue(row, null)); | |
| } | |
| table.Rows.Add(tableRow); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment