Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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

like image 682
GurdeepS Avatar asked Dec 10 '25 07:12

GurdeepS


1 Answers

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));
like image 124
Johannes Rudolph Avatar answered Dec 12 '25 21:12

Johannes Rudolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!