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
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
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));
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;
}