views:

345

answers:

2

I am trying to perform a LINQ query on a DataTable and show the result in another DataTable. My source DataTable looks something like this:

DataTable myDataTable = new DataTable();
myDataTable.Columns.Add("OrderID", typeof(int));
myDataTable.Columns.Add("Date", typeof(DateTime));
myDataTable.Columns.Add("UnitsPurchased", typeof(int));

The resulting DataTable looks like this when filled:

Order ID   Date    Units Purchased  
16548    10/15/09      250  
17984    11/03/09      512   
20349    01/11/10      213  
34872    01/15/10      175

My current LINQ query looks like this:

IEnumerable<DataRow> query = (from row in myDataTable.AsEnumerable()
                              where row.UnitsPurchased > 200
                              select new
                              {
                                 row.OrderID,
                                 row.Date,
                                 row.UnitsPurchased
                              }) as IEnumerable<DataRow>;

resultDataTable.DataSource = query.CopyToDataTable<DataRow>();

Every time I run this code query is null. I can see that that the as IEnumerable<DataRow> is the culprit, but it makes no since to me since DataTable.AsEnumerable() returns an IEnumerable<DataRow>. Any help would be appreciated.

+3  A: 

When you select new { }, you're actually getting an IEnumerable<(Anonymous Type)>, not IEnumerable<DataRow>. So your as IEnumerable<DataRow> will return null, since it can't be directly cast.

Either select new MyDataRow(constructor using values...) or something, or just do var query =... without the as cast. There's an msdn article about using CopyToDataTable with a non-DataRow generic parameter, though I haven't read it in depth, but selecting new DataRows is probably the easier solution.

Tanzelax
A: 
netmatrix01
-1 - That's not "simple"; that is a **horrible** kludge! How can you push that kind of hack on an unsuspecting programmer?
Shaul