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()
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With