SELECT Unique rows from Datagridview using LINQ

穿精又带淫゛_ 提交于 2019-12-12 00:27:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!