【问题标题】:Using LINQ to get DataGridView row index where first column has specific value使用 LINQ 获取第一列具有特定值的 DataGridView 行索引
【发布时间】:2014-06-06 14:15:48
【问题描述】:

我想获取 DataGridViewRow 的索引,其中第一列的值匹配。

到目前为止我的代码:

string SearchForThis = "test";

int index = from r in dgv.Rows
            where r.Cells[0].Value == SearchForThis
            select r.Index;

编译器错误:

找不到源类型“System.Windows.Forms.DataGridViewRowCollection”的查询模式的实现。 '哪里' 没有找到。考虑明确指定范围变量“r”的类型。

【问题讨论】:

  • 尝试将dgv.Rows 替换为dgv.Rows.Array。这行得通吗?

标签: c# linq datagridview


【解决方案1】:

DataGridViewRowCollection 没有实现IEnumerable<T>,这就是为什么你不能使用LINQ,使用Enumerable.Cast 方法。

int index = (dgv.Rows.Cast<DataGridViewRow>()
                    .Where(r => r.Cells[0].Value == SearchForThis)
                    .Select(r => r.Index)).First();

或者使用查询语法:

int index = (from r in dgv.Rows.Cast<DataGridViewRow>()
            where r.Cells[0].Value == SearchForThis
            select r.Index).First();

您需要从集合中返回一个结果,这就是我使用First 的原因,但请记住,如果没有符合条件的项目,它将抛出异常。要克服这一点,请参阅答案末尾的解决方案。

见:Enumerable.Cast&lt;TResult&gt; Method

Cast&lt;TResult&gt;(IEnumerable) 方法启用标准查询 通过提供 必要的类型信息。例如,ArrayList 不会 实现IEnumerable&lt;T&gt;,但通过调用 Cast&lt;TResult&gt;(IEnumerable) 在 ArrayList 对象上,标准 然后可以使用查询运算符来查询序列。

(您也可以使用Enumerable.OfType 方法,它会忽略所有不是DataGridViewRow,但使用DataGridView,Cast 也可以)

也可以使用FirstOrDefault先获取行,再获取索引,如:

int index = 0;
var item = dgv.Rows.Cast<DataGridViewRow>()
                    .FirstOrDefault(r => r.Cells[0].Value == (object)1);
if (item != null)
    index = item.Index;

【讨论】:

    【解决方案2】:

    我通常喜欢这些形式,(尽管 Rows 不是正确的集合这一事实在语法上很烦人):

     var hit = dgv.Rows.Cast<DataGridViewRow>().First(row => row.Cells["MyColumnName"].Value.Equals(MyIndexValue));
    
     var hit = dgv.Rows.Cast<DataGridViewRow>().FirstOrDefault(row => row.Cells["MyColumnName"].Value.Equals(MyIndexValue));
    

    如果你只想要第一个,那就更简单了:

     var hit = dgv.Rows.Cast<DataGridViewRow>().First(row => row.Cells[0].Value.Equals(MyIndexValue));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-26
      • 2020-11-07
      相关资源
      最近更新 更多