从VB.NET中的List(Of T)中删除重复项

时间:2010-02-23 22:18:58

标签: .net vb.net generics

我无法从列表中删除重复项。我做错了什么?

Dim Contacts As New List(Of Person)

...

' remove duplicates '
Contacts = Contacts.Distinct(New PersonEqualityComparer).ToList

我的平等比较器:

Public Class PersonEqualityComparer
    Implements IEqualityComparer(Of Person)
    Public Function Equals1(ByVal x As Person, ByVal y As Person) As Boolean Implements System.Collections.Generic.IEqualityComparer(Of Person).Equals
        Return String.Equals(x.EmailAddress, y.EmailAddress, StringComparison.CurrentCultureIgnoreCase) AndAlso _
               String.Equals(x.GivenName, y.GivenName, StringComparison.CurrentCultureIgnoreCase) AndAlso _
               String.Equals(x.Surname, y.Surname, StringComparison.CurrentCultureIgnoreCase)
    End Function
    Public Function GetHashCode1(ByVal obj As Person) As Integer Implements System.Collections.Generic.IEqualityComparer(Of Person).GetHashCode
        Return obj.GetHashCode
    End Function
End Class

2 个答案:

答案 0 :(得分:4)

您需要实现GetHashCode1,以便任何两个相等的对象具有相同的哈希码。

如果许多不相等的对象具有相同的哈希码,则执行速度会慢得多,尤其是对于大型列表。换句话说,请勿将其更改为Return 0

在您的情况下,最简单的实现将是这样的:

Return StringComparer.CurrentCultureIgnoreCase.GetHashCode(obj.EmailAddress) _
   Xor StringComparer.CurrentCultureIgnoreCase.GetHashCode(obj.GivenName) _
   Xor StringComparer.CurrentCultureIgnoreCase.GetHashCode(obj.Surname)

如果您想要更强大的实施,请参阅this answer

答案 1 :(得分:1)

StringBuilder sb as New StringBuilder
...concatenate all strings...
return StringComparer.CurrentCultureIgnoreCase.GetHashCode(sb.ToString())

它肯定比 xor 方法慢,或者滚动你自己的正确哈希函数。 但是,如果由于xoring而导致碰撞率很高,则可以尝试使用它。