C# 如何使用 LINQ 查找 DataGridView 行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15098071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:02:33  来源:igfitidea点击:

How can I use LINQ to find a DataGridView row?

c#winformslinqdatagridview

提问by Darrin Doherty

Is there any way to use a LINQ style query to find a DataGridView row? I am trying to find the one bound to a specific object and highlight it.

有没有办法使用 LINQ 样式查询来查找 DataGridView 行?我试图找到绑定到特定对象的那个并突出显示它。

MyDatagrid.Rows.FirstOrDefault(r => r.DataBoundItem == myItem).Selected = true;

Error 1 'System.Windows.Forms.DataGridViewRowCollection' does not contain a definition for 'FirstOrDefault' and no extension method 'FirstOrDefault' accepting a first argument of type 'System.Windows.Forms.DataGridViewRowCollection' could be found (are you missing a using directive or an assembly reference?)

错误 1“System.Windows.Forms.DataGridViewRowCollection”不包含“FirstOrDefault”的定义,并且找不到接受“System.Windows.Forms.DataGridViewRowCollection”类型的第一个参数的扩展方法“FirstOrDefault”(您是否缺少使用指令或程序集引用?)

采纳答案by Lee

You need to cast to IEnumerable<DataGridViewRow>since DataGridViewRowCollectiononly implements IEnumerable:

您需要强制转换为IEnumerable<DataGridViewRow>因为DataGridViewRowCollection仅实现IEnumerable

MyDatagrid.Rows
    .Cast<DataGridViewRow>()
    .FirstOrDefault(r => r.DataBoundItem == myItem).Selected = true;

回答by Sturgus

For those who came here looking for the VB-version, Lee's answer translates to:

对于那些来这里寻找 VB 版本的人,Lee 的回答转化为:

MyDatagrid.Rows.Cast(Of DataGridViewRow)().FirstOrDefault(Function(r) r.DataBoundItem Is myItem).Selected = True

Furthermore, if you're like me, and are using this to find your DataGridViewRowfrom your bound DataTable.DataRow(DataGridView.DataSource = DataTable), then you can access it like this:

此外,如果你像我一样,并且正在使用它DataGridViewRow从你的边界DataTable.DataRow( DataGridView.DataSource = DataTable) 中找到你的,那么你可以像这样访问它:

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

This is much more efficient than looping through your DataGridViewlooking for matching values.

这比循环DataGridView查找匹配值要高效得多。