LINQ without IEqualityComparer implementation

550 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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.)

0
On

Well, build a set of all the nicknames, then run against that.

var nicknames = new HashSet<string>(list2.Select(l2 => l2.Nick));
var newNames = from l1 in list1
               where !nicknames.Contains(l1.Name)
               select l1;