如何删除vb.net中数据表中的所有重复项? [英] How to remove all duplicates in a data table in vb.net?

查看:40
本文介绍了如何删除vb.net中数据表中的所有重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑我的数据表

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

最终输出是

2 BBB
3 CCC
4 DDD

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

How can i remove the rows in the data table using Vb.Net Any help is appreciated.

推荐答案

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

Following works if you only want the distinct rows(skip those with same ID and Name):

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

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

If you want to remove the dups from the original table:

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)

这篇关于如何删除vb.net中数据表中的所有重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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