Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.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行索引检索强制转换要求_C#_.net_Winforms_Linq - Fatal编程技术网

C# LINQ行索引检索强制转换要求

C# LINQ行索引检索强制转换要求,c#,.net,winforms,linq,C#,.net,Winforms,Linq,总之,我在一个DataGridView(DGV)中有行。为了测试添加到此DGV的项是否已经存在,我编写了一个方法,该方法使用以下LINQ查询返回匹配行的行索引(而不是for/foeach循环): IEnumerable rowCol=this.dataGridViewAttachList.Rows.Cast() .Where(row=>row.Cells[(int)DgvColumns.DatabaseName].Value.ToString() .Equals(数据库名、StringCompa

总之,我在一个
DataGridView
(DGV)中有行。为了测试添加到此DGV的项是否已经存在,我编写了一个方法,该方法使用以下LINQ查询返回匹配行的行索引(而不是
for/foeach
循环):

IEnumerable rowCol=this.dataGridViewAttachList.Rows.Cast()
.Where(row=>row.Cells[(int)DgvColumns.DatabaseName].Value.ToString()
.Equals(数据库名、StringComparison.OrdinalIgnoreCase))
.Select(行=>row.Index);
我的问题是:为什么我必须使用
cast()
我第一次尝试不使用它,我花了一段时间才解决这个问题;但我不清楚为什么有必要这样做


谢谢您的时间。

这是因为
DataGridViewRowCollection
实现了
IEnumerable
而不是
IEnumerable
这是因为
DataGridViewRowCollection
实现了
IEnumerable
,而不是
IEnumerable
DataGridView
。行是
DataGridViewRowCollection
,它实现了
IEnumerable
。LINQ扩展方法需要
IEnumerable
DataGridView
。行的类型为
DataGridViewRowCollection
,它实现
IEnumerable
。LINQ扩展方法需要
IEnumerable

这是因为
DataGridViewRowCollection
(行的类型属性)是非通用的
IEnumerable
。因此,要获得linq可以使用的通用版本
IEnumerable
,您应该调用。
Cast()

这是因为
DataGridViewRowCollection
(行的类型属性)是非通用的
IEnumerable
。因此,要获得linq可以使用的通用版本
IEnumerable
,您应该调用。
Cast()

IEnumerable<int> rowCol = this.dataGridViewAttachList.Rows.Cast<DataGridViewRow>()
    .Where(row => row.Cells[(int)DgvColumns.DatabaseName].Value.ToString()
        .Equals(databaseName, StringComparison.OrdinalIgnoreCase))
    .Select(row => row.Index);