问题
I am trying to SELECT ALL rows\columns from a datagridview where the first column is unique using 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
回答1:
First you need import 2 namespaces for distinct with linq to use AsEnumerable() method in DataTables and Field() method in DataRows
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
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
回答2:
The best way to solve this is to write a comparer to compare the entire row.
Dim noduplicates = dgvMaestro.Rows.Cast(Of DataGridViewRow).Distinct(New RowComparer())
There are some examples of comparers on msdn
来源:https://stackoverflow.com/questions/20058026/select-unique-rows-from-datagridview-using-linq