Search code examples
c#linqiequalitycomparer

LINQ without IEqualityComparer implementation


I have 2 collection with different classes. MyClass1 - Name,Age,etc MyClass2 - Nick, Age, etc

I want to find except of this collections. Something like

list1.Exept(list2, (l1,l2) => l1.Name==l2.Nick);

But i cannt write this code and need to implement my own comparer class with IEqualityComparer interface and it's looking very overhead for this small task. Is there any elegant solution?


Solution

  • Except really doesn't work with two different sequence types. I suggest that instead, you use something like:

    var excludedNicks = new HashSet<string>(list2.Select(x => x.Nick));
    var query = list1.Where(x => !excludedNicks.Contains(x.Name));
    

    (Note that this won't perform the "distinct" aspect of Except. If you need that, please say so and we can work out what you need.)