LINQ: How to return all children elements of all parents

Viewed 642

I have IEnumerable<Parent> AllParents. Each parent has IEnumerable<Child> Children. How can I extract all children of all parents into one IEnumerable<Child> AllChildren using LINQ?

Foreach way I'm using now:

var allChildrenList = new List<Child>();
foreach (var parent in AllParents)
{
    allChildrenList.AddRange(parent.Children);
}
AllChildren = allChildrenList;
1 Answers

You can use .SelectMany(),

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

var allChildrens = AllParents.SelectMany(x => x.Children).ToList();

It will iterate over all parents and combine children of all parents to a single list.

Related