简体   繁体   English

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

[英]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. 您需要实现GetHashCode1以便任何两个相等的对象具有相同的哈希码。

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 . 换句话说,不要将其更改为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. 它肯定比xor方法或滚动您自己的适当哈希函数慢。 You may try to use this however, if you have high collision rates because of xoring. 但是,如果由于Xoring导致碰撞率较高,则可以尝试使用此方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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