[Resolvido] LINQ Distinct - IEquatable - Não funcionando
Boa tarde,
Estou tentando usar o DISTINCT em uma consulta LINQ porém não está funcionando.
Implementei tanto a interface IEquatable quando a interface IEqualityComparer mas mesmo assim não é possível distinguir as instâncias.
Alguém já passou por isso? Poderia ajudar?
Desde já obrigado.
Public Class Teste
Implements IEquatable(Of Teste), IEqualityComparer(Of Teste)
Private _Codigo As Integer
Public Property Codigo() As Integer
Get
Return _Codigo
End Get
Set(ByVal value As Integer)
_Codigo = value
End Set
End Property
Public Sub New(id As Integer)
Me.Codigo = id
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Return DirectCast(obj, Teste).Codigo = Me.Codigo
End Function
Public Function Equals1(other As Teste) As Boolean Implements IEquatable(Of Teste).Equals
Return Me.Codigo = other.Codigo
End Function
Public Function Equals2(x As Teste, y As Teste) As Boolean Implements IEqualityComparer(Of Teste).Equals
Return x.Codigo = y.Codigo
End Function
Public Function GetHashCode1(obj As Teste) As Integer Implements IEqualityComparer(Of Teste).GetHashCode
Return DirectCast(obj, Teste).Codigo
End Function
End Class
Testando:
Dim p1 As New Teste(78)
Dim p2 As New Teste(78)
Dim l As New List(Of Teste) From {p1, p2}
MsgBox(l.Distinct().Count())
MsgBox(l.Distinct().ToList().Count)
Discussão (2)
Carregando comentários...