Hi,
I’m having a simple problem, but I don’t know what is wrong. I’m trying to remove all duplicate records from a DataTable using the following code:

Private Function removeDuplicate(ByVal dTable As DataTable) As DataTable
        Dim row1 As DataRow
        Dim row2 As DataRow
        Const wantedColumn As Int16 = 1
        Dim tableSize As Integer = dTable.Rows.Count
        For i As Integer = 0 To tableSize - 2
            row1 = dTable.Rows(i)
            For j As Integer = i + 1 To tableSize - 1
                row2 = dTable.Rows(j)
                If j >= tableSize Then
                    Exit For
                End If
                If row1(wantedColumn) = row2(wantedColumn) Then
                    row2.Delete()
                    tableSize = tableSize - 1
                End If
            Next
        Next
        Return dTable
    End Function

The problem is: even though I’m updating the tableSize every time a row is deleted, it seems that the For loops are iterating until the original size (for original size I mean the dataTable size before any record be deleted). Does anyone have any ideas about what is wrong?

Does anyone have any ideas about what is wrong?

You need to use the do/while or do/until loop instead and use an integer value to loop through all the items. Because the for loops store the top number at the beginning of the enumartion, deleting a row should not be allow.

I haven't tried this but the general idea should be correct.

Dim iOutRow As Integer = 0
        Dim iNrow As Integer = 0
        Dim dtTemp As New DataTable()

        Do While Not iOutRow = dtTemp.Rows.Count - 1
            iNrow = 0
            Do While Not iNrow = dtTemp.Rows.Count - 1
                If dtTemp.Rows(iNrow) Is dtTemp.Rows(iOutRow) AndAlso Not iNrow = iOutRow Then
                    dtTemp.Rows.RemoveAt(iNrow)
                    iOutRow -= 1
                    Continue Do
                End If
                iNrow += 1
            Loop
            iOutRow += 1
        Loop

Edit: Looking back onto my code, it'd be better if you had a field value to verify rather than the rows being identical as there is an issue of deleting the first row. Hope this gets you on your way though; let me know what you come up with.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.