Click here to Skip to main content
15,909,199 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I have a problem,

I need to delete duplicate entries in an List that I created.
The list is classed as an object and each line has multiple entries.

Can anyone give me any guidance or tutorials to try, because everything that I have tried so far hasn't worked?
(I have searched on Google, and no success)

I know I can't use For Each...Next because you cannot delete entries in an IEnumerable list, however using a For Next loop brings up an error. i.e:

VB
For i As Integer = 0 To mylist.Items.Count - 1 Step 1
Posted
Updated 14-Sep-12 4:25am
v3

The list remove was created for this purpose, however it deletes the first simular item in the list:
http://msdn.microsoft.com/en-us/library/cd666k3e.aspx[^]
 
Share this answer
 
I couldn't understand what you mean by "List". "List(Of T)" or "ListBox" or something else...
So I will give a general answer.
When you remove an item from a list, item count of this list decreases. This is why fixed loops don't work as expected. I wrote a method below that removes duplicated items in a ListBox object. You can adapt this method to your purpose...
VB
Private Sub RemoveDupItems(ByRef ListBoxObj As ListBox)
    Dim ItemCount As Integer = ListBoxObj.Items.Count
    Dim Position1 As Integer = 0

    While (Position1 < ItemCount)
        Dim Position2 As Integer = 0
        While (Position2 < ItemCount)
            If Position1 <> Position2 Then
                If ListBoxObj.Items(Position1) = ListBoxObj.Items(Position2) Then
                    ListBoxObj.Items.RemoveAt(Position2)
                    ItemCount -= 1
                    Exit While
                End If
            End If
            Position2 += 1
        End While
        Position1 += 1
    End While
End Sub

Usage example:
VB
RemoveDupItems(ListBox1)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900