views:

180

answers:

2

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()
+2  A: 

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

Stephen Cleary
+3  A: 

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

public class MyComparer : IEqualityComparer<ICustomer>
{
    public bool Equals(ICustomer x, ICustomery)
    {
        // Match whatever
        return ((x.FirstName == y.FirstName) &&
                (x.LastName == y.LastName));
    }
}

C# useage for the two options (feel free to edit to make this VB syntax):

.Distinct(new MyComparer())
.Union(custNameMatch, new MyComparer())

Here is my attempt at the VB (used a c# to VB.NET tool) so it could be wrong:

Dim allMatch = shortNameMatch.Union(custNameMatch).Distinct(New MyComparer())
Dim allMatch = shortNameMatch.Union(custNameMatch, New MyComparer())
Kelsey
That rocked. Thought I might need something like that, but couldn't find it anywhere.
Anthony Potts