SELECT使用LINQ从Datagridview选择唯一的行 [英] SELECT Unique rows from Datagridview using LINQ

查看:175
本文介绍了SELECT使用LINQ从Datagridview选择唯一的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从datagridview中选择所有的行\列,其中第一列使用LINQ是唯一的。

I am trying to SELECT ALL rows\columns from a datagridview where the first column is unique using LINQ.

Datagridview:

Datagridview:

1     Blue     1111
1     Blue     1111
2     Green    1234
3     Orange   3211
2     Green    1234
4     Red      2222

尝试获取此输出:

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

输出:

1
2
3
4

谢谢

推荐答案

首先,您需要导入2个不同于linq的命名空间,以在DataTows中使用AsEnumerable()方法和DataRows中的Field()方法

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

声明新的datatable



Declare new datatable

Dim NewTbl As New System.Data.DataTable

在您的场景中添加列

NewTbl.Columns.Add("ID", GetType(Integer))
NewTbl.Columns.Add("Color", GetType(String))
NewTbl.Columns.Add("Value", GetType(Integer))

Linq使用Table'TblValues'作为数据源

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

现在你有一个DataTable'NewTbl'在

Now you have a DataTable 'NewTbl' with distinct values inside

这篇关于SELECT使用LINQ从Datagridview选择唯一的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆