The following C# code demonstrates SelectMany being used in a coupe of different ways. I’ve collated example from a couple of sources here (Nick’s Blog, MSDN, and StackOverflow). They demonstrate a couple of different ways to use the SelectMany LINQ extension method.

Sample 1: shows the way that SelectMany can unwrap a list of lists into a list.

Sample 2: shows an interesting way of detecting duplicates. This solution returns a list of the strings with more than 1 occurrence (Skip(1)), as a list of n-1 copies of string (where n is the number of times that string occurs). So if you just want the duplicated string (occurring only once), put a Distinct() after the SelectMany. This example also invokes an interesting property of the GroupBy and what is returned the IGrouping interface, I’ll comment on that below.

Sample 3: Is a demonstration of a lambda expression working within a class which contains a list.

This is the output from the LINQ GroupBy extension method. The example 2 lead me to ponder “How does it work?”. Having worked with (around) the LINQ GroupBy extension method previously, I knew that there was a Key property, and a list of contributors to the group. So, how did the Skip(1) work?

It turns out that IGrouping is a bit of an “interesting animal”. The description of the interface is as follows: