本文介绍了在VB.NET中删除List(Of T)中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法从我的列表中删除重复项。

  Dim联系人作为新人名单(人物)

...

删除重复的
联系人= Contacts.Distinct(New PersonEqualityComparer).ToList

我的等号比较器:

 公共类PersonEqualityComparer 
实现IEqualityComparer(Of Person)
公共函数Equals1(ByVal x As Person,ByVal y As Person)As Boolean实现System.Collections.Generic.IEqualityComparer(Of Person).Equals
返回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.IEqualit yComparer(Of Person).GetHashCode
返回obj.GetHashCode
End Function
End Class


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

b
$ b

如果许多不相等的对象具有相同的散列码,它将执行得更慢,特别是对于大型列表。换句话说,不要将它改为返回0



在你的情况中,最简单的实现是像这样:

$ p $ 返回StringComparer.CurrentCultureIgnoreCase.GetHashCode(obj.EmailAddress)_
Xor StringComparer.CurrentCultureIgnoreCase.GetHashCode( obj.GivenName)_
Xor StringComparer.CurrentCultureIgnoreCase.GetHashCode(obj.Surname)

如果你想要一个更强大的实现,请参阅。


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.

这篇关于在VB.NET中删除List(Of T)中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 04:30