查找重复项并使用Linq在新的datagridview中显示

时间:2015-01-05 19:44:30

标签: vb.net excel csv datagridview

我有两个datagridviews:

DataGridView1: 这是使用以下代码从csv文件生成的:

For Each line As String In System.IO.File.ReadAllLines("C:\path\test.csv")
                Form1.DataGriView1.Rows.Add(line.Split(";"))
 Next

The.csv文件具有以下格式:

12345;有些文字; 2000000; 12345678901; 2014-07-31;

23456;有些文字; 2000000; 10987654321; 2014-07-11;

DataGridView2 这是使用以下代码生成的excel文件:

 Dim MyConnection As System.Data.OleDb.OleDbConnection
            Dim DtSet As System.Data.DataSet
            Dim MyCommand As System.Data.OleDb.OleDbDataAdapter

            MyConnection = New System.Data.OleDb.OleDbConnection _
                ("provider=Microsoft.Jet.OLEDB.4.0; Data Source='C:\Users\path\excel.xls'; Extended Properties=Excel 8.0;")
            MyCommand = New System.Data.OleDb.OleDbDataAdapter _
                    ("select * from [Sheet$]", MyConnection)
            DtSet = New System.Data.DataSet
            MyCommand.Fill(DtSet)
            Form1.DataGridView2.DataSource = DtSet.Tables(0)
            MyConnection.Close()

Excel文档有6列,带有标题。

This is how the datagridview are named

问题:

我需要找到重复项并在第三个gridview中显示数据。具体来说,我想看看DataGridView1中列column1中的值是否在DataGridView2中的列polnr中。如果是这样,我希望将DataGridView中的整行复制到DataGridView3

我今天正在使用此代码,但问题是它太慢了......

Dim rowlist As New ArrayList     Dim dgv3row As New DataGridViewRow

For Each dgv1row As DataGridViewRow In DataGridView1.Rows
    For Each dgv2row As DataGridViewRow In DataGridView2.Rows

        If dgv1row.Cells("Column1").Value = dgv2row.Cells("polnr").Value Then

            For Each dgvcell As DataGridViewCell In dgv1row.Cells
                rowlist.Add(dgvcell.Value)
            Next

            If rowlist.Count > 0 Then
                Dim dgv3rowindex As Integer = DataGridView3.Rows.Add()

                dgv3row = DataGridView3.Rows(dgv3rowindex)

                For Each dgv3cell As DataGridViewCell In dgv3row.Cells
                    dgv3cell.Value = rowlist(dgv3cell.ColumnIndex)
                Next

                rowlist.Clear()
            End If
        End If
    Next
Next

我的问题是:这是一种更快捷的方式吗?像LINQ或其他东西?

1 个答案:

答案 0 :(得分:0)

您可以使用LINQ查询重复记录:

Dim dupRecords = (From data1 As DataGridViewRow In DataGridView1.Rows
                          Join data2 As DataGridViewRow In DataGridView2.Rows
                          On data1.Cells("Column1").Value Equals data2.Cells("polnr").Value
                          Select data2).ToList

然后遍历重复的行结果并添加到第3个datagridview。以下假设列已在第3个datagridview中创建:

Dim rowIndex As Integer = 0

For Each row In dupRecords
   For cellIndex As Integer = 0 To row.Cells.Count - 1
     DataGridView3.Rows(rowIndex).Cells(cellIndex).Value = _
        row.Cells(cellIndex).Value
   Next cellIndex
   rowIndex += 1
Next row