Get differences between two list
12,190
Solution 1
Try Except
with Union
, but you'll need to do it for both in order to find differences in both.
var exceptions = list1.Except(list2).Union(list2.Except(list1)).ToList();
OR as a Linq alternative, there could be a much faster approach: HashSet.SymmetricExceptWith():
var exceptions = new HashSet(list1);
exceptions.SymmetricExceptWith(list2);
Solution 2
IEnumerable<string> differenceQuery = list1.Except(list2);
http://msdn.microsoft.com/en-us/library/bb397894.aspx
Author by
Mehrdad
Software Developer & Designer System Analyst C# Python
Updated on June 17, 2022Comments
-
Mehrdad almost 2 years
I have a 2 lists of an object type:
List<MyClass> list1;
List<MyClass> list2;
What is the best way (performance and clean code) to extract differences in data between these two List?
I mean get objects that is added, deleted, or changed (and the change)? -
mattytommo about 12 yearsThat won't give you the items only in list 2 :)
-
Darren about 12 years@MitchWheat - why does it matter about the time I posted the answer?