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

点点圈 提交于 2019-12-07 08:17:37

问题


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?


回答1:


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") });



回答2:


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"));
    }
}


来源:https://stackoverflow.com/questions/2560776/why-doesnt-enumerablerowcollectiondatarow-select-compile-like-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!