grady
grady

Reputation: 12755

Using Where on a list which is contained in another list?

Let's say I have a list called list1. This list1 contains another list, called list2. Now I want to check if list2 in list1 contains certain elements and return another list.

list3 = list1.list2.Where(p => p.something == 1)

Something like that?

Upvotes: 0

Views: 1142

Answers (2)

Itay Karo
Itay Karo

Reputation: 18286

Take a look at the SelectMany function.

Upvotes: 1

Cheng Chen
Cheng Chen

Reputation: 43523

This solution will return conditioned items in the inner list.

var result = list.SelectMany(l => l.InnerList)
                 .Where(p => p.something == 1);

If you want to get items in the outer list which meets the condition, use:

var another = list.Where(l => l.InnerList.Any(p => p.something == 1));

Upvotes: 2

Related Questions