2010-04-01 114 views
3

这工作:为什么EnumerableRowCollection <DataRow> .Select()这样编译?

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

,但是,这并不:

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

我也试过:

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

望着。选择的两个重载()方法,我认为后两者都应该返回EnumerableRowCollection,但显然我错了。我错过了什么?

回答

3

问题是你要结合执行LINQ查询(查询语法和直接调用LINQ扩展方法)两种方式。行from x in table.AsEnumerable()不是有效的查询,因为它至少需要select ...。这应该工作:

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

只需添加到这...你正在过滤'x'的表格,但没有为它选择任何东西......你可以保持相同的语法,只需添加'选择x'最后。 – Edyn 2012-07-31 15:51:53

0

也许问题出在别的地方。这将编译就好:

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

你res2是不相同的我的。李的答案是解决方案。在后两个例子中使用方法语法时,我错误地使用了“from x”。其中,巧合的是,你没有:) – 2010-04-01 14:03:52