C# 使用LINQ获取DataGridView行索引,其中第一列具有特定值
我想获取DataGridViewRow的索引,其中第一列的值匹配 到目前为止,我的代码是: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
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));