如何检查一个值是否重复,如果重复需要删除数据表中的两行

How to check if a value is duplicate and if duplicate need to delete both line in Datatable

我有一个只有几行数据的数据表,我的目的是检查是否有重复值,如果有重复行,我认为重复值&我需要删除创建重复的两行。

输入

我的预期输出是

任何建议都会有所帮助

提前致谢

感谢和问候 戒日

您需要某种方法来为每一行获取唯一值,该值仅取决于行中的数据,这通常称为 hash value

然后你可以使用任何你喜欢的方法 bin the data 并且只选择有一个项目的垃圾箱。

例如,表单上只有一个 DataGridView 和一个按钮:

Public Class Form1

    Dim dt As New DataTable

    Function RowHash(dr As DataRow) As Long
        'TODO: Make a hash function which will not overflow a Long.
        Dim h As Long = 0
        For Each itm In dr.ItemArray
            h = (31 * h) + itm.GetHashCode()
        Next

        Return h

    End Function

    Sub MakeTestData()
        dt.Columns.Add("Name")
        dt.Columns.Add("P")
        For i = 0 To 9
            Dim nr = dt.NewRow()
            nr("Name") = Chr(65 + (i Mod 6))
            nr("P") = i Mod 6
            dt.Rows.Add(nr)
        Next

        DataGridView1.DataSource = dt

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim newDataTable = dt.Clone()
        Dim uniqueData = dt.AsEnumerable().
            GroupBy(Function(r) RowHash(r)).
            Select(Function(s) New With {.n = s.Count, .data = s.First().ItemArray}).
            Where(Function(t) t.n = 1)

        For Each u In uniqueData
            Dim nr = newDataTable.NewRow()
            nr.ItemArray = u.data
            newDataTable.Rows.Add(nr)
        Next

        DataGridView1.DataSource = newDataTable

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        MakeTestData()

    End Sub

End Class

点击按钮前后: