LINQ to Objects.Distinct () does not extend individual objects

I have two ways that I perform a fuzzy search for a client. One for the short name, and the other for the customer’s name. When I take these two sets of results and then combine them (I read several places to remove individual values), I get duplicates. Thinking that all I have to do is call the .Distinct() method, I also get duplicates. Do I need to implement some comparison functions in my client object? My code is:

  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() 
+4
source share
2 answers

You need to create an equalizer and use it in 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()) 
+6
source

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

+2
source

Source: https://habr.com/ru/post/1310298/


All Articles