LINQ 区别不工作

LINQ Distinct Not Working

我正在尝试 select 与我的 class 不同的实例,但它不起作用,即使在实施 IEqualityComparer(如此处所述:https://msdn.microsoft.com/en-us/library/bb338049.aspx)和 IEquatable[=13= 之后也是如此]

有人可以帮忙吗?

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

测试:

Dim p1 As New Teste(78)
Dim p2 As New Teste(78)
Dim l As New List(Of Teste) From {p1, p2}
MsgBox(l.Count())
MsgBox(l.Distinct().Count())

我有两个消息框都显示“2”。

您需要告诉 Distinct 方法使用什么相等比较器。我也会把它拆分成它自己的 class。例如:

Public Class TesteEqualityComparer 
    Implements IEqualityComparer(Of Teste)

    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 obj.Codigo.GetHashCode()
    End Function
End Class

现在您的查询是:

MsgBox(l.Distinct(New TesteEqualityComparer()).Count())