Published Saturday, March 03, 2007 4:08 AM by mtaulty

"Orcas" March CTP - IEnumerable<T> to DataTable

In the May CTP which I played with previously I could take an arbitrary resultset and force it into a DataTable. There was an extension method called something like ToDataTable which did this for you.

I can't find one of these in the MarchCTP so I built a very rough and ready one;

namespace LocalExtensions
{
 public static class TableExtensions
 {
  public static DataTable MT_MakeDataTable<T>(
   this IEnumerable<T> list, CreateRowDelegate<T> fn)
  {
   DataTable table = new DataTable();  

   foreach (T t in list)
   {
    object[] rowData = fn(t);

    if (table.Columns.Count == 0)
    {
     for (int i = 0; i < rowData.Length; i++)
     {
      table.Columns.Add();
     }
    }
    table.Rows.Add(rowData);
   }
   return (table);
  }
  public delegate object[] CreateRowDelegate<T>(T t);
 }
}

You'd have to call this with something like;

   DataTable resultsTable = results.MT_MakeDataTable(row =>
    new object[] { row.Customer, row.Order, row.TotalSales });

I tried to avoid using reflection to generate the column names but it'd be something you could easily add. Ideally I'd like to get rid of the new object[] at the call site as well but a way of doing that didn't pop straight into my head and so I left it.

I wonder if there is a built-in way of doing this in the March CTP? Sure, it's inefficient but it's still kind of useful in some places.

# Converting a LINQ to Entities query to a DataTable @ Friday, September 07, 2007 10:03 AM

Julie Lerman Blog