vb.net从listview中删除重复项的最快方法?

时间:2017-04-14 15:00:09

标签: vb.net listview duplicates

有没有人有更快更好的方法从列表视图中删除重复项?我目前正在这样做:我按字母顺序对项目进行排序,然后检查下面的项目并将其与上面的项目进行比较。

虽然这很费时..当我在excel表中输入20.000条记录,并删除重复项时需要几毫秒,但是使用下面的代码需要花费数小时来检查vb.net中的20.000项。有谁知道更快的方法?

 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

2 个答案:

答案 0 :(得分:0)

使用仅接受唯一值的HashSet

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

然后将项目从HashSet设置为ListView

答案 1 :(得分:0)

以下是基于Linq的解决方案,可根据item.Text获取不同的项目并对项目进行排序。如果不需要排序,您可以删除OrderBy部分。

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