Find all objects using lambda

I have List<Person>

(people), every person has List<Kid>

(children)

If I want to find all children, in LINQ this is what I will do

var kids=new List<Kids>();

foreach(var p in people)
{
    foreach(var kid in p.Kids)
    {
         kids.Add(kid);
    }
}

      

Is there one way to do this using LINQ?

+3


source to share


3 answers


It's as simple as SelectMany :

Projects each element of a sequence onto an IEnumerable and flattens the resulting sequences into one sequence.



var kids = people.SelectMany(p => p.Kids);

      

(If you want List<Kid>

instead IEnumerable<Kid>

, just call .ToList()

the result.)

+13


source


You can use SelectMany extension method



var kids = new List(people.SelectMany(person => person.Kids));

      

+4


source


The "LINQ-not-lambda-style" version SelectMany

:

var allKids = 
  from p in people
  from k in p.Kids  // secondary "from" makes SelectMany (aka flat map)
  select k;

// Result from above is IEnumerable, to Force evaluation as a List:
List<Kid> allKidsList = allKids.ToList();

      

+3


source







All Articles