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!
(you can also call
ToList()
afterExcept()
, if you don't like referencing lazy collections.)The
Except()
method compares the values using the default comparer, if the values being compared are of base data types, such asint
,string
,decimal
etc.Otherwise the comparison will be made by object address, which is probably not what you want... In that case, make your custom objects implement
IComparable
(or implement a customIEqualityComparer
and pass it to theExcept()
method).You could do something like this:
Since the Except extension method operates on two IEumerables, it seems to me that it will be a O(n^2) operation. If performance is an issue (if say your lists are large), I'd suggest creating a HashSet from list1 and use HashSet's ExceptWith method.
If both your lists implement IEnumerable interface you can achieve this using LINQ.