4

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?

David Fox
  • 10,603
  • 9
  • 50
  • 80

2 Answers2

4

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") });
Lee
  • 142,018
  • 20
  • 234
  • 287
  • Just to add to this... you're filtering table for 'x', but not selecting anything for it... you could keep the same syntax and just add 'select x' at the end. – Edyn Jul 31 '12 at 15:51
0

Maybe the problem is somewhere else. This compiles just fine:

using System.Data;

class Program
{
    static void Main(string[] args)
    {
        var dt = new DataTable();

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

        var res2 = dt.AsEnumerable()
            .Where(y => y.Field<string>("something") == "value")
            .Select(y => y.Field<decimal>("decimalfield"));
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • your res2 is not identical to mine. Lee's answer is the solution. i incorrectly used a "from x" when using method syntax in the latter two examples. which, coincidentally, you did not :) – David Fox Apr 01 '10 at 14:03