c# – Combining subcollections into one collection with Linq

Question:

there are classes

public class B{
}

public class A{
  public List<B> ListB = new List<B>();
}

there is a list of classes List<A> ListA = new List<A>();

how to merge all ListB from ListA into one array or sheet or any other IEnumerable<B> collection using Linq methods

Answer:

Use the SelectMany function

var listsB = ListA.SelectMany(x=>x.ListB);

Or its query syntax

var listsB = from a in ListA
             from b in a.ListB
             select b;
Scroll to Top