简体   繁体   中英

Remove duplicates from a List(Of T) in VB.NET

I fail to remove duplicates from my List. What am I doing wrong?

Dim Contacts As New List(Of Person)

...

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

my equality comparer:

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

You need to implement GetHashCode1 so that any two equal objects have the same hashcode.

If many unequal objects have the same hashcode, it will perform much more slowly, especially for large lists. In other words, don't change it to Return 0 .

In your case, the simplest implementation would be like this:

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

If you want a more robust implementation, see this answer .

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

It is certainly slower than the xor method or rolling your own proper hash function. You may try to use this however, if you have high collision rates because of xoring.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM