Find Differences Between Two Collections






4.71/5 (10 votes)
Find differences between two collections
Introduction
Having an existing collection of objects and a new collection of objects, we need to find out which objects were added to the original collection and which were removed from it.
Background
The easiest way to understand this is to think of collections as sets A and B. A is the existing collection and B is the new collection.
Objects that were removed from A are the ones that are in A but are not in B.
Objects that were added to the collection are the ones that are in B but are not in A.
The Code
Let us write the above statements in code.
public static void Compare<T>(List<T> existing, List<T> updated,
out List<T> added, out List<T> removed) where T : IComparable
{
// New identifiers are the ones that are in updated but not in existing.
added = updated.Except(existing).ToList();
// Deleted identifiers are the ones that are in existing but not in updated.
removed = existing.Except(updated).ToList();
}
And we're done. Yes it is that simple. Once someone shows you how to do it.