How to merge a collection of collections in Linq

LinqCollectionsLinq to-Objects

Linq Problem Overview


I would like to be able to fusion an IEnumerable<IEnumerable<T>> into IEnumerable<T> (i.e. merge all individual collections into one). The Union operators only applies to two collections. Any idea?

Linq Solutions


Solution 1 - Linq

Try

var it = GetTheNestedCase();
return it.SelectMany(x => x);

SelectMany is a LINQ transformation which essentially says "For Each Item in a collection return the elements of a collection". It will turn one element into many (hence SelectMany). It's great for breaking down collections of collections into a flat list.

Solution 2 - Linq

var lists = GetTheNestedCase();
return
    from list in lists
    from element in list
    select element;

is another way of doing this using C# 3.0 query expression syntax.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoannes VermorelView Question on Stackoverflow
Solution 1 - LinqJaredParView Answer on Stackoverflow
Solution 2 - LinqJoe ChungView Answer on Stackoverflow