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.
I think you want HashSet.Except. That is, rather than use Lists, use HashSets, and then the operation is available. This is a better type if what you are representing is really a 'set' anyway. (If you already have a list, you can just create a 'new HashSet' out of it.)
IEnumerable<T> a, b;
var added = a.Except(b);
var removed = b.Except(a);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With