Schanckopotamus Schanckopotamus - 1 year ago 58
C# Question

Using Linq Except not Working as I Thought

List1 contains items { A, B } and List2 contains items { A, B, C }.

What I need is to be returned { C } when I use Except Linq extension. Instead I get returned { A, B } and if I flip the lists around in my expression the result is { A, B, C }.

Am I misunderstanding the point of Except? Is there another extension I am not seeing to use?

I have looked through and tried a number of different posts on this matter with no success thus far.

var except = List1.Except(List2); //This is the line I have thus far

EDIT: Yes I was comparing simple objects. I have never used IEqualityComparer, it was interesting to learn about.

Thanks all for the help. The problem was not implementing the comparer. The linked blog post and example below where helpful.

Answer Source

If you are storing reference types in your list, you have to make sure there is a way to compare the objects for equality. Otherwise they will be checked by comparing if they refer to same address.

You can implement IEqualityComparer<T> and send it as a parameter to Except() function. Here's a blog post you may find helpful.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download