如何删除vb.net中数据表中的所有重复项?

时间:2011-10-07 11:36:37

标签: vb.net

考虑我的数据表

ID Name
1  AAA
2  BBB
3  CCC
1  AAA
4  DDD

最终输出

2 BBB
3 CCC
4 DDD

如何使用Vb.Net删除数据表中的行 任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:6)

如果你只想要不同的行(跳过那些具有相同ID和名称的行),以下工作:

Dim distinctRows = From r In tbl
       Group By Distinct = New With {Key .ID = CInt(r("ID")), Key .Name = CStr(r("Name"))} Into Group
       Where Group.Count = 1
       Select Distinct
' Create a new DataTable containing only the unique rows '
Dim tblDistinct = (From r In tbl
       Join distinctRow In tblDistinct
       On distinctRow.ID Equals CInt(r("ID")) _
       And distinctRow.Name Equals CStr(r("Name"))
       Select r).CopyToDataTable

如果要从原始表中删除重复项:

Dim tblDups = From r In tbl
       Group By Dups = New With {Key .ID = CInt(r("ID")), Key .Name = CStr(r("Name"))} Into Group
       Where Group.Count > 1
       Select Dups
Dim dupRowList = (From r In tbl
       Join dupRow In tblDups
       On dupRow.ID Equals CInt(r("ID")) _
       And dupRow.Name Equals CStr(r("Name"))
       Select r).ToList()

For Each dup In dupRowList 
    tbl.Rows.Remove(dup)
Next

以下是您的样本数据:

Dim tbl As New DataTable
tbl.Columns.Add(New DataColumn("ID", GetType(Int32)))
tbl.Columns.Add(New DataColumn("Name", GetType(String)))
Dim row = tbl.NewRow
row("ID") = 1
row("Name") = "AAA"
tbl.Rows.Add(row)
row = tbl.NewRow
row("ID") = 2
row("Name") = "BBB"
tbl.Rows.Add(row)
row = tbl.NewRow
row("ID") = 3
row("Name") = "CCC"
tbl.Rows.Add(row)
row = tbl.NewRow
row("ID") = 1
row("Name") = "AAA"
tbl.Rows.Add(row)
row = tbl.NewRow
row("ID") = 4
row("Name") = "DDD"
tbl.Rows.Add(row)

答案 1 :(得分:0)

您可以使用DataTable的DefaultView.ToTable方法进行如下过滤:

 Public Sub RemoveDuplicateRows(ByRef rDataTable As DataTable)
    Dim pNewDataTable As DataTable
    Dim pCurrentRowCopy As DataRow
    Dim pColumnList As New List(Of String)
    Dim pColumn As DataColumn

    'Build column list
    For Each pColumn In rDataTable.Columns
        pColumnList.Add(pColumn.ColumnName)
    Next

    'Filter by all columns
    pNewDataTable = rDataTable.DefaultView.ToTable(True, pColumnList.ToArray)

    rDataTable = rDataTable.Clone

    'Import rows into original table structure
    For Each pCurrentRowCopy In pNewDataTable.Rows
        rDataTable.ImportRow(pCurrentRowCopy)
    Next
End Sub