LINQ区别不起作用

时间:2018-06-14 17:42:34

标签: vb.net linq distinct iequalitycomparer iequatable

我正在尝试从我的类中选择不同的实例,但它不起作用,即使在实现IEqualityComparer(如此处所述:https://msdn.microsoft.com/en-us/library/bb338049.aspx)和IEquatable

之后也是如此

有人可以帮忙吗?

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())

我有两个msgbox都显示“2”。

1 个答案:

答案 0 :(得分:2)

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

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())