-8

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?

user1186050
  • 10,710
  • 18
  • 92
  • 235
  • 6
    tons of duplicate – Royi Namir Jul 31 '13 at 20:33
  • 2
    ... and it's not a question. It's a request. What have you tried so far? – stakx - no longer contributing Jul 31 '13 at 20:33
  • possible duplicate of [Dynamic LINQ OrderBy on IEnumerable](http://stackoverflow.com/questions/41244/dynamic-linq-orderby-on-ienumerablet) – Richard Jul 31 '13 at 20:34
  • possible duplicate of [C# Is String in Array](http://stackoverflow.com/questions/501194/c-sharp-is-string-in-array) – DACrosby Jul 31 '13 at 21:00
  • Off topic? Closed as off topic? What is going on in this place? Do we not answer questions any more? – jason Jul 31 '13 at 21:17
  • 2
    @jason this is a poorly asked question that shows no effort to find a solution, and is a likely duplicate. But you are correct that it is on topic. – Eric Lippert Jul 31 '13 at 21:37
  • @Eric Lippert: I would agree with all of that. But this: "poorly asked question" *and* "that shows no effort to find a solution" are unfortunately *both* true for a very large fraction of the questions that I stumble upon on this site. – jason Jul 31 '13 at 21:48
  • Two questions are linked as possible duplicates of this one. It is not the case that this question is a duplicate of either of those. Additionally, the accepted answer in those questions should not be used to establish an answer for this question. – jason Jul 31 '13 at 22:19

3 Answers3

10
var allIn = !l2.Except(l1).Any();
Sergey Berezovskiy
  • 215,927
  • 33
  • 392
  • 421
9

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).

jason
  • 220,745
  • 31
  • 400
  • 507
-1

here you go

 bool b = l2.All( s => l1.Contains(s));