Mike Taulty's Blog
Bits and Bytes from Microsoft UK
"Orcas" March CTP - IEnumerable<T> to DataTable
Mike Taulty's Blog

Mike's Badges

Follow on Twitter
View mike's profile on slideshare
Add to Technorati Favorites
CW Blog Awards

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.


Posted Sat, Mar 3 2007 4:08 AM by mtaulty

Comments

Julie Lerman Blog wrote Converting a LINQ to Entities query to a DataTable
on Fri, Sep 7 2007 10:03 AM
(C) Mike Taulty, 2009. All rights reserved. The information in this weblog is provided "AS IS" with no warranties, and confers no rights. This weblog does not represent the thoughts, intentions, plans or strategies of my employer. It is solely my opinion. Inappropriate comments will be deleted at the authors discretion. All code samples are provided "AS IS" without warranty of any kind, either express or implied, including but not limited to the implied warranties of merchantability and/or fitness for a particular purpose.
Powered by Community Server (Non-Commercial Edition), by Telligent Systems