How to combine a collection of collections in Linq

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

+45
collections linq linq-to-objects
Nov 26 '08 at 16:03
source share
2 answers

Try

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

SelectMany is a LINQ transformation that essentially says: "For each item in the collection, the items in the collection are returned." It will turn one element into many (hence, SelectMany). This is great for breaking collections of collections into a flat list.

+80
Nov 26 '08 at 16:05
source share
 var lists = GetTheNestedCase(); return from list in lists from element in list select element; 

is another way to do this using C # 3.0's query expression syntax.

+13
Apr 21 '09 at 21:33
source share



All Articles