Check if several values ​​(stored in the selected collection) are in the LINQ collection, in the query

What is a method in LINQ to provide a collection of values ​​and to check if any of these values ​​are in the collection?

thank

+3
source share
3 answers

You can emulate this through .Intersect()and check if the intersection set has all the necessary elements. I think this is pretty inefficient, but quick and dirty.

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

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

List<T> list = ...
List<T> shouldBeContained = ...
bool containsAll = (shouldBeContained.All(x=>list.Contains(x));
+4
source

Linq has a number of operators that can be used to test for the existence of one set of values ​​in another.

Intersect:

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

0

, ... , :

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

Source: https://habr.com/ru/post/1733359/


All Articles