Posts Tagged ‘Brain Improvement’

SelectMany Example: Flatten Parent Child Association Into A Single List

October 28, 2011

I’m starting to get the hang of LINQ SelectMany now.

Here’s a great article which explains SelectMany better than any other I’ve read. For this James Etheredge is awarded the BTWT Golden Tadpole With Anachronistic Zeppelin for services to Brain Improvement.

So the key is to recognise that SelectMany needs a List to work on. Well, not a List exactly. SelectMany actually works on an IEnumerable. But to get started with SelectMany we can take the conceptual shortcut of thinking of SelectMany as working on instances of List.

So if I have a list of Tadpoles each of which contains a list of Zeppelins and I want to flatten that list I just say:

List (Of TadpoleZeppelins) tadZeps = tadpoles.SelectMany(tad =>

CreateTadpoleZeppelin creates a list of TadpoleZeppelins out of a List of Zeppelins, like so:

CreateTadpoleZeppelin(List(Of Zeppelin) zeps)
List(Of TadpoleZeppelin) tadZeps = new List (Of TadpoleZeppelen)
zeps.ForEach(zep =>
TadpoleZeppelin tadZep = new TadpoleZeppelin();
tadZep.NumFins = zep.Tadpole.NumFins;
tadZep.HeliumCapacity = zep.HeliumCapacity;


return tadZeps;

I think that’s pretty self-explanatory.

If the example seems a bit weird just substitute ‘Customer’ for ‘Tadpole’ and ‘Order’ for ‘Zeppelin’