gpt4 book ai didi

c# - 使用 LINQ 获取第一列具有特定值的 DataGridView 行索引

转载 作者:太空狗 更新时间:2023-10-29 21:12:51 25 4
gpt4 key购买 nike

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

最佳答案

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<TResult> Method

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 也可以)

您还可以使用 FirstOrDefault先获取行然后获取索引,如:

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

关于c# - 使用 LINQ 获取第一列具有特定值的 DataGridView 行索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24083959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com