tags:

views:

50

answers:

3

Hi,

What is the method in LINQ to supply a collection of values and check if any/all of these values are in a collection?

Thanks

+1  A: 

You can emulate this via .Intersect() and check if the intersection set has all the required elements. I guess this is pretty inefficient but quick and dirty.

List<T> list = ...
List<T> shouldBeContained = ...
bool containsAll = (list.Intersect(shouldBeContained).Count == shouldBeContained.Count)

Or you could do it with .All(). I guess this is more efficient and cleaner:

List<T> list = ...
List<T> shouldBeContained = ...
bool containsAll = (shouldBeContained.All(x=>list.Contains(x));
Johannes Rudolph
A: 

Linq has a number of operators that can be used to check existence of one set of values in another.

I would use Intersect:

Produces the set intersection of two sequences by using the default equality comparer to compare values.

Oded
A: 

While there's nothing easy that is built in...you could always create extension methods to make life easier:

public static bool ContainsAny<T>(this IEnumerable<T> data,
    IEnumerable<T> intersection)
{
    foreach(T item in intersection)
        if(data.Contains(item)
            return true;
    return false;
}

public static bool ContainsAll<T>(this IEnumerable<T> data,
    IEnumerable<T> intersection)
{
    foreach(T item in intersection)
        if(!data.Contains(item))
            return false;
    return true;
}
Justin Niessner