0

I have a list of the object inside a list. I want a list of objects based on some condition.

List<List<int>> lists = new List<List<int>> {
    new List<int> {1, 2, 3},
    new List<int> {4, 5, 6},
    new List<int> {7, 8, 9},
};

If I do something like

lists.Select(x => x.Where(y => y < 5));

I will get a List<List<int>>

But, I actually want List. How can I get all the elements smaller than 5 as a List<int>?

PS: I know I can use for loop, but that's not what I want.

  • 4
    Does this answer your question? [Difference Between Select and SelectMany](https://stackoverflow.com/questions/958949/difference-between-select-and-selectmany) – Preben Huybrechts Jul 14 '20 at 18:49
  • Now, it makes sense after reading the answer. I was not sure how to use Where() with SelectMany(). Thanks! – Avadh Vashisth Jul 14 '20 at 18:58

1 Answers1

1

You can utilize SelectMany function provided by linq

var result = lists.SelectMany(x => x).Where(y => y < 5).ToList();
Manprit Singh Sahota
  • 1,279
  • 2
  • 14
  • 37