Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用LINQ获取DataGridView行索引,其中第一列具有特定值_C#_Linq_Datagridview - Fatal编程技术网

C# 使用LINQ获取DataGridView行索引,其中第一列具有特定值

C# 使用LINQ获取DataGridView行索引,其中第一列具有特定值,c#,linq,datagridview,C#,Linq,Datagridview,我想获取DataGridViewRow的索引,其中第一列的值匹配 到目前为止,我的代码是: string SearchForThis = "test"; int index = from r in dgv.Rows where r.Cells[0].Value == SearchForThis select r.Index; 编译器错误: 找不到源类型“System.Windows.Forms.DataGridViewRowCollection

我想获取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”的类型。

<代码> DATAGIDVIEW视图集合> /COD>不执行<代码> iQueLabe<代码>,这就是为什么不能使用LINQ,使用方法。
我通常喜欢这些表单(尽管行不是一个合适的集合这一事实在语法上很烦人):

var hit=dgv.Rows.Cast().First(row=>row.Cells[“MyColumnName”].Value.Equals(MyIndexValue));
var hit=dgv.Rows.Cast();
如果您只想要第一个,它会变得更简单:

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

尝试将
dgv.Rows
替换为
dgv.Rows.Array
。这样行吗?
int index = (from r in dgv.Rows.Cast<DataGridViewRow>()
            where r.Cells[0].Value == SearchForThis
            select r.Index).First();
int index = 0;
var item = dgv.Rows.Cast<DataGridViewRow>()
                    .FirstOrDefault(r => r.Cells[0].Value == (object)1);
if (item != null)
    index = item.Index;
 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));