Friday, April 1, 2011

Impedance MisMatch: IEnumerable<T> to DataTable

I had to work with a class that consumed a System.DataTable today. DataTable is an old class that pre-dates generics in the CLR. DataTable carries typed data as an array of System.Object - double plus yuck! As you can imagine the code I use these days has compiler verified type safety by using IEnumerable everywhere. So how did I convert from my beloved IEnumerable to the yucky DataTable? With reflection of course! This simple method solves our problems:



public static DataTable ToDataTable(IEnumerable rows)
{
var tableToReturn = new DataTable();

// get properties of T
var properties = typeof (T).GetProperties().Where(p => p.MemberType == MemberTypes.Property);

// Convert T's properties to columns in the DataTable
foreach (var p in properties)
{
tableToReturn.Columns.Add(p.Name, p.PropertyType);
}

//populate rows
foreach (var row in rows)
{
T row1 = row;
var propertyValuesAsEnumerable = properties.Select(p => p.GetValue(row1, null));
tableToReturn.Rows.Add(propertyValuesAsEnumerable.ToArray());
}
return tableToReturn;
}

0 comments:

Post a Comment