Anders
Anders

Reputation: 521

vb.net fastest way to remove duplicates from listview?

Does anyone have a quicker and better way to remove duplicates from a listview? I am currently doing it like this: I sort the items alphabetically, and then it checks the item below and compares it with the one above.

This is time consuming though.. When I enter 20.000 records into an excel sheet, and remove duplicates it takes a few miliseconds, but with this code below it takes hours to check 20.000 items in vb.net. Does anyone know of a faster method?

 Dim max As Integer = ListView2.Items.Count
    Dim i As Integer = 0

    For Each item As ListViewItem In ListView2.Items

        If i = max Then
            Exit For
        End If

        If i > 0 Then

            If item.Text = ListView2.Items(i - 1).Text Then
                max -= 1
                item.Remove()
                i -= 1
            End If
        End If

        i += 1

        Label4.Text = "Total domains: " & ListView2.Items.Count

    Next

Upvotes: 0

Views: 1642

Answers (2)

TnTinMn
TnTinMn

Reputation: 11801

Here is a Linq based solution to get distinct items based on item.Text and sort the items. If sorting is not required, you can remove the OrderBy part.

Private Shared Sub RemoveDuplicatesAndSort(lv As ListView)
    Dim distictItems As ListViewItem() = lv.Items.Cast(Of ListViewItem)().Distinct(New LVItemComparer()).OrderBy(Function(item As ListViewItem) item.Text).ToArray
    lv.BeginUpdate() ' suppress screen updates
    lv.Items.Clear()
    lv.Items.AddRange(distictItems)
    lv.EndUpdate()
End Sub

Private Class LVItemComparer : Implements IEqualityComparer(Of ListViewItem)
    Public Function Equals1(x As ListViewItem, y As ListViewItem) As Boolean Implements IEqualityComparer(Of ListViewItem).Equals
        Return x.Text.Equals(y.Text)
    End Function

    Public Function GetHashCode1(obj As ListViewItem) As Integer Implements IEqualityComparer(Of ListViewItem).GetHashCode
        Return obj.Text.GetHashCode
    End Function
End Class

Upvotes: 1

Fabio
Fabio

Reputation: 32445

Use HashSet which will accept only unique values.

Dim itemsText = ListView2.Items.Cast(Of ListViewItem).Select(Function(item) item.Text)
Dim uniquesValues As HashSet(Of String) = New HashSet(Of String)(itemsText)   

Then set items from HashSet to the ListView.

Upvotes: 0

Related Questions