Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Find Differences Between Two Collections

4.71/5 (12 votes)
16 Jun 2016CPOL 12.5K  
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.

C#
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)