开发者

Check if multiple values (stored in a dedicated collection) are in a LINQ collection, in query

开发者 https://www.devze.com 2022-12-20 09:02 出处:网络
What is the method in LINQ to supply a collection of values and check if any/all of these values are in a开发者_StackOverflow中文版 collection?

What is the method in LINQ to supply a collection of values and check if any/all of these values are in a开发者_StackOverflow中文版 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));


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消