Is there a way to get the difference between two sets of objects in c#

SiC picture SiC · Apr 30, 2009 · Viewed 16.8k times · Source

I want to get the difference between two sets of ints in c#. Given s1 and s2 I want to return those ints which are in s1 and not in s2. I can do something such as:

    List<int> s1 = new List<int>();
    List<int> s2 = new List<int>();

    foreach (int i in s1)
    {
        if (s1.Contains(i))
        {
            //
        }
        else
        {
            //
        }
    }

But I was wondering if anyone can point out anything cleaner. I would like to do something such as

List<int> omitted = s1.Difference(s2);

Not sure if there is an existing method or a LINQ construct that anyone might be able to point out? Thank you.

Answer

leppie picture leppie · Apr 30, 2009
IEnumerable<T> a, b;

var added = a.Except(b);
var removed = b.Except(a);