Skip to content

Instantly share code, notes, and snippets.

@Jtorrecilla
Created February 16, 2016 06:52
Show Gist options
  • Select an option

  • Save Jtorrecilla/90db81d28bd6be991c6c to your computer and use it in GitHub Desktop.

Select an option

Save Jtorrecilla/90db81d28bd6be991c6c to your computer and use it in GitHub Desktop.
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