Why doesn't EnumerableRowCollection<DataRow>.Select() compile like this?

David Fox picture David Fox · Apr 1, 2010 · Viewed 7.3k times · Source

This works:

from x in table.AsEnumerable()
where x.Field<string>("something") == "value"
select x.Field<decimal>("decimalfield");

but, this does not:

from x in table.AsEnumerable()
.Where(y=>y.Field<string>("something") == "value")
.Select(y=>y.Field<decimal>("decimalfield"));

I also tried:

from x in table.AsEnumerable()
.Where(y=>y.Field<string>("something") == "value")
.Select(y=>new { name = y.Field<decimal>("decimalfield") });

Looking at the two overloads of the .Select() method, I thought the latter two should both return EnumerableRowCollection, but apparently I am wrong. What am I missing?

Answer

Lee picture Lee · Apr 1, 2010

The problem is you're combining two ways of performing a linq query (query syntax and calling the linq extension methods directly). The line from x in table.AsEnumerable() is not a valid query since it require at least a select .... This should work:

table.AsEnumerable() 
.Where(y=>y.Field<string>("something") == "value") 
.Select(y=>new { name = y.Field<decimal>("decimalfield") });