Click here to Skip to main content
15,890,717 members
Articles / Programming Languages / C#
Tip/Trick

Find Differences Between Two Collections

Rate me:
Please Sign up or sign in to vote.
4.71/5 (12 votes)
16 Jun 2016CPOL 12.2K   7   3
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)


Written By
Founder Wischner Ltd
United Kingdom United Kingdom
Writing code since 1982 and still enjoying it.

Comments and Discussions

 
QuestionAn FYI on List<> and Enumerable.Except() Pin
Dan Gorman17-Jun-16 12:19
Dan Gorman17-Jun-16 12:19 
AnswerRe: An FYI on List<> and Enumerable.Except() Pin
Tomaž Štih17-Aug-16 22:20
Tomaž Štih17-Aug-16 22:20 
SuggestionDon't forget to implement IComparable Pin
mldisibio17-Jun-16 8:25
mldisibio17-Jun-16 8:25 
Just a reminder that for any type T that is not a value type, you will have to implement IComparable<T>, otherwise the default comparison is based on reference equality only.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.