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?
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));
I have an extension method that uses the existing Contains()-method. I find it more intuitive than using Instersect() or Except().
public static bool ContainsAll<T>(this IEnumerable<T> source, IEnumerable<T> values)
{
return values.All(value => source.Contains(value));
}
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
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