vb.net 使用 LINQ 从 Datagridview 中选择唯一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20058026/
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
SELECT Unique rows from Datagridview using LINQ
提问by Force
I am trying to SELECT ALL rows\columns from a datagridview where the first column is unique using LINQ.
我正在尝试使用 LINQ 从数据网格视图中选择所有行\列,其中第一列是唯一的。
Datagridview:
数据网格视图:
1 Blue 1111
1 Blue 1111
2 Green 1234
3 Orange 3211
2 Green 1234
4 Red 2222
Trying to get this Output:
试图获得此输出:
1 Blue 1111
2 Green 1234
3 Orange 3211
4 Red 2222
I was able to use the following code which pulls all unique records from the first column but I am not sure how to get the remaining columns:
我能够使用以下代码从第一列中提取所有唯一记录,但我不确定如何获取其余列:
Dim unique() As String = (From row As DataGridViewRow In dgvMaestro.Rows.Cast(Of DataGridViewRow)() _
Where Not row.IsNewRow _
Select CStr(row.Cells(0).Value)).Distinct.ToArray
For Each a As String In unique
Debug.Print(a)
Next
Output:
输出:
1
2
3
4
Thanks
谢谢
回答by James K
First you need import 2 namespaces for distinct with linq to use AsEnumerable() method in DataTables and Field() method in DataRows
首先,您需要使用 linq 导入 2 个不同的命名空间,以便在 DataTables 中使用 AsEnumerable() 方法和在 DataRows 中使用 Field() 方法
Imports System.Data.DataTableExtensions
Imports System.Data.DataRowExtensions
Declare new datatable
声明新的数据表
Dim NewTbl As New System.Data.DataTable
Add columns in you scenario
在您的场景中添加列
NewTbl.Columns.Add("ID", GetType(Integer))
NewTbl.Columns.Add("Color", GetType(String))
NewTbl.Columns.Add("Value", GetType(Integer))
Linq use Table 'TblValues' as you datasource
Linq 使用 Table 'TblValues' 作为数据源
Dim results = (From row in TblValues.AsEnumerable() select col1 = row(Of Integer)("ID"), col2 = row(Of String)("Color"), col3 = row(Of Integer)("Value")).Distinct().ToList()
Iterate elements in results with for each, the reason is because results is an object datarow collection and isn't convert auto to table
为每个迭代结果中的元素,原因是结果是一个对象数据行集合,而不是自动转换为表
For each r in results
Dim Row as System.Data.DataRow = NewTbl.NewRow
Row("ID") = r.col1
Row("Color") = r.col2
Row("Value") = r.col3
NewTbl.Rows.Add(Row)
next
Now you have a DataTable 'NewTbl' with distinct values inside
现在你有一个 DataTable 'NewTbl' 里面有不同的值

