2012-02-08 60 views
4

我对DataGridViewRowCollection上的LINQ查询有点神秘。这里是我的查询(其中“网格”是一个DataGridView对象):LINQ to DataGridViewRowCollection

var rows = from DataGridViewRow row in grid.Rows 
      where row.Selected 
      select row; 

我有一个包含此查询一个项目,它完美地被执行。问题是,在另一个项目中,我得到以下错误,当我尝试构建解决方案:

error CS1936: Could not find an implementation of the query pattern for source type 'System.Windows.Forms.DataGridViewRow'. 'Where' not found. 

起初我还以为这是一个参考的问题,但我使用在两个项目中相同的参考:

using System; 
using System.Collections; 
using System.Collections.Generic; 
using System.Collections.Specialized; 
using System.Data; 
using System.Data.EntityModel; 
using System.Drawing; 
using System.Linq; 
using System.Linq.Expressions; 
using System.Text; 
using System.Text.RegularExpressions; 
using System.Windows.Forms; 
using System.Reflection; 
using System.Runtime.InteropServices; 
using System.Security.Cryptography; 
using System.Diagnostics; 

没有人有任何想法,为什么我的LINQ查询将在一个项目工作,而不是其他?

编辑1:

为了记录在案,这里是确切的上下文在查询工作:

public List<Int64> ComponentIDs 
{ 
    get 
    { 
     return 
      (
       from DataGridViewRow row in grid.Rows 
       where row.Selected 
       select (Int64)row.Cells[0].Value 

      ).ToList(); 

    } 

} 

编辑2:

我只是碰到以下link ...看到接受的答案...这就是我想要做的。出于某种原因,我无法使IEnumerable.Cast()扩展方法正常工作......我错过了什么?

+1

你确定你有* *正好在这两个地方同样的LINQ查询? (顺便说一句,那些使用的是指令,而不是引用,名称空间和程序集之间有很大的区别。) – 2012-02-08 14:33:51

+0

谢谢,Jon纠正了我对“reference”这个词的不正确使用! =)是的,我在两个地方都使用完全相同的LINQ查询。我必须承认这很令人困惑。 – HydroPowerDeveloper 2012-02-08 14:46:54

+1

[在LINQ中使用DataGridViewRowCollection对象]可能的重复(http://stackoverflow.com/questions/2648657/using-datagridviewrowcollection-object-in-linq) – KyleMit 2016-04-11 20:29:46

回答

6

其实我不认为你的代码看起来完全一样的。由于DataGridViewRowCollection没有实现IEnumerable<DataGridViewRow>您必须使用Cast<DataGridViewRow>()这样的:

var rows = from row in grid.Rows.Cast<DataGridViewRow>() 
      where row.Selected 
      select row; 
+0

嗨Magnus ...谢谢你的回复。我可以向你保证,我的代码看起来和我发布它的方式完全一样。我似乎没有Cast <>()扩展方法...我怎么能得到这个? – HydroPowerDeveloper 2012-02-08 19:42:02

+0

嗨马格努斯...请参阅我的编辑2. – HydroPowerDeveloper 2012-02-08 19:46:58

+0

你可以在'System.Linq.Enumerable.Cast'找到它# – Magnus 2012-02-08 20:07:20

1

尝试LINQ查询改写到:

var rows = dgv.Rows 
      .Where(x => x.Selected); 
+0

感谢瑞克,感谢您的快速响应。我试着你的建议,我得到了另一个错误:错误CS1061:'System.Windows.Forms.DataGridViewRowCollection'不包含'Where'的定义和没有扩展方法'Where'接受类型'System.Windows的第一个参数。 Forms.DataGridViewRowCollection'可以找到(你是否缺少使用指令或程序集引用?) – HydroPowerDeveloper 2012-02-08 14:36:29