I Have two generic list filled with CustomsObjects.
I need to retrieve the difference between those two lists(Items who are in the first without the items in the second one) in a third one.
I was thinking using .Except()
was a good idea but I don't see how to use this..
Help!
Using
Except
is exactly the right way to go. If your type overridesEquals
andGetHashCode
, or you're only interested in reference type equality (i.e. two references are only "equal" if they refer to the exact same object), you can just use:If you need to express a custom idea of equality, e.g. by ID, you'll need to implement
IEqualityComparer<T>
. For example:Then use:
Note that this will remove any duplicate elements. If you need duplicates to be preserved, it would probably be easiest to create a set from
list2
and use something like:I think important to emphasize - using Except method will return you items who are in the first without the items in the second one only. It does not return those elements in second that do not appear in first.
But if you want get real difference between two lists:
Items who are in the first without the items in the second one and items who are in the second without the items in the first one.
You need using Except twice:
Or you can use SymmetricExcerptWith method of HashSet. But it changes the set on which called:
bit late but here is working solution for me
In above mention code I am getting the properties difference between my base class and derived class list