C# 如何使用LINQ查找DataGridView行?
是否有任何方法可以使用LINQ样式的查询来查找DataGridView行?我试图找到绑定到特定对象的对象并高亮显示它C# 如何使用LINQ查找DataGridView行?,c#,winforms,linq,datagridview,C#,Winforms,Linq,Datagridview,是否有任何方法可以使用LINQ样式的查询来查找DataGridView行?我试图找到绑定到特定对象的对象并高亮显示它 MyDatagrid.Rows.FirstOrDefault(r => r.DataBoundItem == myItem).Selected = true; 错误1“System.Windows.Forms.DataGridViewRowCollection”不包含“FirstOrDefault”的定义,并且找不到接受“System.Windows.Forms.Data
MyDatagrid.Rows.FirstOrDefault(r => r.DataBoundItem == myItem).Selected = true;
错误1“System.Windows.Forms.DataGridViewRowCollection”不包含“FirstOrDefault”的定义,并且找不到接受“System.Windows.Forms.DataGridViewRowCollection”类型的第一个参数的扩展方法“FirstOrDefault”(缺少using指令或程序集引用吗?)
您需要强制转换到
IEnumerable
,因为DataGridViewRowCollection
仅实现IEnumerable
:
MyDatagrid.Rows
.Cast<DataGridViewRow>()
.FirstOrDefault(r => r.DataBoundItem == myItem).Selected = true;
MyDatagrid.Rows
.Cast()
.FirstOrDefault(r=>r.DataBoundItem==myItem).Selected=true;
对于那些来这里寻找VB版本的人,Lee的答案是:
MyDatagrid.Rows.Cast(Of DataGridViewRow)().FirstOrDefault(Function(r) r.DataBoundItem Is myItem).Selected = True
此外,如果您像我一样,正在使用此命令从绑定的DataTable.DataRow
(DataGridView.DataSource=DataTable
)中查找您的DataGridView行
),那么您可以这样访问它:
Dim MyDataRowSearch() As DataRow = MyDataTable.Select("SomeColumn = SomeValue")
If MyDataRowSearch.Count = 1 Then
MyDataGrid.Rows.Cast(Of DataGridViewRow)().FirstOrDefault(Function(r) DirectCast(r.DataBoundItem, DataRowView).Row Is MyDataRowSearch(0)).Selected = True
End If
这比在DataGridView
中循环查找匹配值要高效得多