从2个数据表中删除重复项

时间:2016-01-29 21:38:41

标签: vb.net

我有2个数据表和列X.如果列x值在两个数据表中,我想删除整行。做这个的最好方式是什么?这就是我尝试过的但不确定这是不是最好的方法。

Private Function SplitData(ByVal dtSome As DataTable, ByVal dtAll As DataTable) As DataTable
    ' This Routine Creates the Plant DataDictionary

    Dim SomelIndex As Integer = 0
    Do While SomelIndex < dtSome.Rows.Count
        Dim AlllIndex As Integer = 0
        Do While AlllIndex < dtAll.Rows.Count
            If dtAll.Rows(AlllIndex).Item("x").ToString = dtSome.Rows(SomelIndex).Item("x").ToString Then
                'I have the below to removes because it doesn't appear to actually remove the rows even if it gets here  
                '  dtAll.Rows.RemoveAt(AlllIndex)

                dtAll.Rows.Remove(dtAll.Rows(AlllIndex))
                Exit Do
            Else
                AlllIndex += 1
            End If
        Loop
        SomelIndex += 1
    Loop

    Return dtAll


End Function

3 个答案:

答案 0 :(得分:1)

您可以使用LINQ查找公共行,然后将其删除。

Private Function SplitData(ByVal dtSome As DataTable, ByVal dtAll As DataTable) As DataTable
    ' This Routine Creates the Plant DataDictionary

    Dim common = (
        From r1 In dtAll.AsEnumerable()
        Join r2 In dtSome.AsEnumerable() On r1("x") Equals r2("x")
        Select r1
    ).ToList()

    For Each r In common
        dtAll.Rows.Remove(r)
    Next

    Return dtAll

End Function

我不知道这是不是最好的&#34;方式,但对我来说,它比嵌套循环更容易看到发生了什么。

请注意,DataTable.AsEnumerable需要引用System.Data.DataSetExtensions.dll

答案 1 :(得分:0)

在您返回dtAll之前,请添加以下行:

dtAll.AcceptChanges()

它将提交您自&#34;上次调用AcceptChanges后所做的更改&#34; ...或者在您的特定情况下,因为您调用了该函数。

答案 2 :(得分:0)

不确定我的问题是什么,但这是一个更简洁的解决方案。我没有使用2执行while循环,而是使用for each和Do While循环。问题不是最有效的方法,但下面绝对有效并删除数据

Public Shared Function SplitDataTables(ByVal dtSome As DataTable, ByVal dtAll As DataTable) As DataTable

    For Each drSome As DataRow In dtSome.Rows
        Dim intIndex As Integer = 0
        Do While intIndex < dtAll.Rows.Count
            If drSome.Item("X").ToString = dtAll.Rows(intIndex).Item("X").ToString Then
                dtAll.Rows.Remove(dtAll.Rows(intIndex))
                Exit Do
            Else
                intIndex += 1
            End If
        Loop
    Next

    Return dtAll

End Function