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);