LINQ to Objects .Distinct() not pulling distinct objects

孤街醉人 提交于 2019-12-05 15:15:16
Kelsey

You need to create an equality comparer and use it in the Union or Distinct:

Public Class MyComparer
    Implements IEqualityComparer(Of ICustomer)

    Public Overloads Function Equals(ByVal x As ICustomer, ByVal y As ICustomer) _
        As Boolean Implements _
        System.Collections.Generic.IEqualityComparer(Of ICustomer).Equals
        Return ((x.id = y.id) AndAlso (x.title = y.title))
    End Function
    Public Overloads Function GetHashCode(ByVal obj As ICustomer) _
        As Integer Implements _
        System.Collections.Generic.IEqualityComparer(Of ICustomer).GetHashCode
        Return Me.GetHashCode()
    End Function
End Class

Usage example:

Dim allMatch = shortNameMatch.Union(custNameMatch).Distinct(New MyComparer())
Dim allMatch = shortNameMatch.Union(custNameMatch, New MyComparer())

Union will remove duplicates. If you need to apply a condition other than reference equality, pass an IEqualityComparer<ICustomer> into Union.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!