使用LINQ获取DataGridView行索引,其中第一列具有特定值 [英] Using LINQ to get DataGridView row index where first column has specific value
问题描述
我想获取DataGridViewRow的索引,其第一列的值与之匹配.
I'd like to get the index of a DataGridViewRow, where the value of its first column matches.
到目前为止,我的代码:
My code so far:
string SearchForThis = "test";
int index = from r in dgv.Rows
where r.Cells[0].Value == SearchForThis
select r.Index;
编译器错误:
找不到源类型'System.Windows.Forms.DataGridViewRowCollection'的查询模式的实现.找不到哪里".考虑明确指定范围变量'r'的类型.
Could not find an implementation of the query pattern for source type 'System.Windows.Forms.DataGridViewRowCollection'. 'Where' not found. Consider explicitly specifying the type of the range variable 'r'.
推荐答案
DataGridViewRowCollection
没有实现IEnumerable<T>
,这就是为什么您不能使用LINQ的原因,请使用
DataGridViewRowCollection
doesn't implement IEnumerable<T>
, that is why you can't use LINQ, use Enumerable.Cast method.
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
的原因,但是请记住,如果没有符合条件的项目,它将抛出异常.要克服这一点,请参阅答案末尾的解决方案.
You will need to get a single result back from the collection, that is why I have used First
, but remember if there are no items matching the criteria, it will throw an exception. To overcome that see the solution at the end of answer.
请参阅: Enumerable.Cast<TResult> Method
Cast<TResult>(IEnumerable)
方法启用标准查询 通过提供 必要的类型信息.例如,ArrayList
不会 实现IEnumerable<T>
,但通过调用ArrayList
对象上的Cast<TResult>(IEnumerable)
,标准 然后可以使用查询运算符查询序列.
The
Cast<TResult>(IEnumerable)
method enables the standard query operators to be invoked on non-generic collections by supplying the necessary type information. For example,ArrayList
does not implementIEnumerable<T>
, but by callingCast<TResult>(IEnumerable)
on theArrayList
object, the standard query operators can then be used to query the sequence.
(您也可以使用Enumerable.OfType
方法,该方法将忽略所有不是DataGridViewRow
的内容,但使用DataGridView
时,Cast也可以)
(You can also use Enumerable.OfType
method, that will ignore all those which are not DataGridViewRow
, but with DataGridView
, Cast is fine as well)
您还可以使用FirstOrDefault
首先获取行,然后获取索引,例如:
You can also use FirstOrDefault
to get the row first and then get the index like:
int index = 0;
var item = dgv.Rows.Cast<DataGridViewRow>()
.FirstOrDefault(r => r.Cells[0].Value == (object)1);
if (item != null)
index = item.Index;
这篇关于使用LINQ获取DataGridView行索引,其中第一列具有特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!