Mohammad Dayyan
Mohammad Dayyan

Reputation: 22409

Contains in Linq to Object?

I have the following Lists :

var list1 = new List<string> {"m1", "m2", "m3"};
var list2 = new List<List<string>> 
    {
        new List<string>{"m1", "m2", "m3"},//1
        new List<string>{"m1", "m2", "m3", "m4", "m5"},//2
        new List<string>{"m4", "m5", "m3", "m45", "m35"},//3
        new List<string>{"m1", "m36", "m43", "m54", "m54"},//4
        new List<string>{"m2", "m4", "m3", "m44", "m55"}//5
    };

I wanna select each list of list2 that contains all elements of list1.
How should we do it in an optimize way

Upvotes: 0

Views: 59

Answers (2)

p.s.w.g
p.s.w.g

Reputation: 148980

You could do use the Except and Any methods:

var results = list2.Where(x => !list1.Except(x).Any())

Upvotes: 2

Juli&#225;n Urbano
Juli&#225;n Urbano

Reputation: 8488

list2.Where(l2 => list1.Intersect(l2).Count()==list1.Count)

Upvotes: 2

Related Questions