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
                    tableSize = tableSize - 1
                End If
        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?

9 Years
Discussion Span
Last Post by Stevoni

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
                    iOutRow -= 1
                    Continue Do
                End If
                iNrow += 1
            iOutRow += 1

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.