SelectMany Example: Flatten Parent Child Association Into A Single List

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(
tad.Zeppelins.ToList())).ToList();

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;

tadZeps.Add(tadZep);
});

return tadZeps;
}

I think that’s pretty self-explanatory.

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

Advertisements

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: