tags:

views:

924

answers:

4

Given two sets of values:

var subset = new[] { 2, 4, 6, 8 };

var superset = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

how do I determine if superset contains all elements of subset?

I have come up with this:

superset.Intersect(subset).Count() == subset.Count()

Is this the most logical and efficient method?

+1  A: 

You could use Except and the resulting count should be 0.

Read up on MSDN for details of the parameters.

Example:

subset.Except(superset).Count() == 0
leppie
It's a lot more efficient to do !Any() vs. Count() == 0. Count() will walk the entire enumerable while Any() will just look for the first element.
JaredPar
+14  A: 

Count? How about Not Any?

bool contained = !subset.Except(superset).Any();
David B
+1 Any() is much more efficient than Count()
JaredPar
Ah very good, I was stuck in the "Intersect" mindset. Thanks for the tip!
Bryan Watts
Much better than count. This would also stop on the first non-match found, if I'm not mistaken.
configurator
+2  A: 

So, my other answer was pretty easy to use. But it's an O(n*m) solution.

Here's a slightly less friendly O(n+m) solution. This should be used if superset is HUGE. It avoids repeatedly enumerating superset.

HashSet<int> hashSet = new HashSet<int>(superset);
bool contained = subset.All(i => hashSet.Contains(i));
David B
+1  A: 

Duplicate of LINQ: Check whether an Array is a subset of another

Cameron MacFarland
Hmmm, didn't see that when searching initially. Thanks.
Bryan Watts