I have two
List<string>
l1 = {"one", "two","three","four"}
l2 = {"one", "three"}
I want to know if all of l2 is inside l1 as a bool?
I have two
List<string>
l1 = {"one", "two","three","four"}
l2 = {"one", "three"}
I want to know if all of l2 is inside l1 as a bool?
Use Enumerable.Except
:
var contained = !l2.Except(l1).Any();
Note that several people have proposed the following:
var contained = l2.All(x => l1.Contains(x));
Let me explain why this is not the best solution, and should be avoided.
The main reason is because it's slower. It's slower because for every item in l2
, it does a linear scan through l1
, over and over for every item in l2
. Let m
be the length of l1
and n
be the length of l2
. So that's a scan through m
items, done n
times. Thus, total cost is O(m * n)
. The alternative would build two hash tables with O(1)
amortized lookup. Building the hash tables is O(m)
and O(n)
respectively. Then, for each of n
items, check if the item is in the hash table. That's O(n)
, amortized. Thus, total cost is O(m + n)
.
here you go
bool b = l2.All( s => l1.Contains(s));