Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a sequence contains all elements of another sequence using Linq [duplicate]

Tags:

c#

linq

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?

like image 286
Bryan Watts Avatar asked Jan 02 '09 19:01

Bryan Watts


3 Answers

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));
like image 180
Amy B Avatar answered Nov 01 '22 09:11

Amy B


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));
}
like image 14
Anders Avatar answered Nov 01 '22 10:11

Anders


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
like image 4
leppie Avatar answered Nov 01 '22 09:11

leppie