How to Remove Duplicate (defined column) Rows from a DataTable

If you want remove the records from a datatable for specified fields are duplicate then the below code is very helpful..
Ex: one datatable having 6 columns.....
like ID,Name,Address,DOB,Department,Salary
and if you remove the records which having Name,Address and DOB is duplicate the just try with below code.

VB.NET
Dim DT As New DataTable
DT = DataLayer.FillDatatable("SELECT * FROM BCPPS_BAFMst")
RemoveDuplicate(DT)
DataGridView1.DataSource = DT

below is the "RemoveDuplicate" Method

Public Shared Sub RemoveDuplicate(ByRef table As DataTable)
Dim keyColumns As New List(Of String)()
keyColumns.Add("Name")
keyColumns.Add("Address")
keyColumns.Add("DOB")
Dim uniquenessDict As New Dictionary(Of String, String)(table.Rows.Count)
Dim stringBuilder As StringBuilder = Nothing
Dim rowIndex As Integer = 0
Dim row As DataRow
Dim rows As DataRowCollection = table.Rows

While rowIndex < rows.Count - 1
row = rows(rowIndex)
stringBuilder = New StringBuilder()

For Each colname As String In keyColumns
stringBuilder.Append(DirectCast(row(colname), Decimal))
Next
If uniquenessDict.ContainsKey(stringBuilder.ToString()) Then
rows.Remove(row)
Else
uniquenessDict.Add(stringBuilder.ToString(), String.Empty)
rowIndex += 1
End If
End While
End Sub

Regards
Santosh

Remove Duplicate Records From DataTable

If you want to remove the duplicate records from a datatable then follow the below code:
VB.NET
Dim distinctTable As DataTable = dtRecords.DefaultView.ToTable(True, "ID", "Name", "Address")
Dim ht As New Hashtable
Dim DuplicateArrList As New ArrayList
For Each dr As DataRow In dtRecords.Rows

If (ht.Contains(dr(ColName))) Then

DuplicateArrList.Add(dr)
Else
ht.Add(dr(ColName), String.Empty)

End If
Next
For Each dr1 As DataRow In DuplicateArrList
dtRecords.Rows.Remove(dr1)
Next
Return dtRecords

Regards
Santosh