Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to Objects .Distinct() not pulling distinct objects

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.GetCustomersByShortName(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()
like image 979
Anthony Potts Avatar asked Feb 28 '23 00:02

Anthony Potts


1 Answers

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())
like image 60
Kelsey Avatar answered Apr 06 '23 15:04

Kelsey