开发者

LINQ to Objects .Distinct() not pulling distinct objects

开发者 https://www.devze.com 2022-12-30 17:58 出处:网络
I have two ways that I am doing a fuzzy search for a customer. One is by an abbreviated name and the other is by the customer\'s full name. When I take these two result sets and then union them togeth

I have two ways that I am doing a fuzzy search for a customer. One is by an abbreviated name and the other is by the customer's full name. When I take these two result sets and then union them together (which I have read several places should remove distinct values) I get duplicates. Thinking that all I need to do is then call the .Distinct() method on this, I also still get duplicates. Do I need to implement some compare functionality in my customer object? My code:

        Dim shortNameMatch As List(Of ICustomer) = CustomerLibrary.GetCustomersByShortNa开发者_运维知识库me(term)
        Dim custNameMatch As List(Of ICustomer) = CustomerLibrary.GetCustomersByCustName(term)
        Dim allMatch = (From a In (From s In shortNameMatch Select s).Union(From c In custNameMatch Select c) Select a).Distinct()


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消