使用LINQ获取DataGridView行索引,其中第一列具有特定值 [英] Using LINQ to get DataGridView row index where first column has specific value

查看:154
本文介绍了使用LINQ获取DataGridView行索引,其中第一列具有特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取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 implement IEnumerable<T>, but by calling Cast<TResult>(IEnumerable) on the ArrayList 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆