Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining IEnumerables in C#?

Is there a simple built-in way to take an ordered list of IEnumerables and return a single IEnumerable which yields, in order, all the elements in the first, then the second, and so on.

I could certainly write my own, but I wanted to know whether there was already a way to accomplish this seemingly useful task before I do it.

like image 709
recursive Avatar asked Feb 08 '09 18:02

recursive


2 Answers

Try SelectMany.

IEnumerable<int> Collapse(IEnumerable<IEnumerable<int>> e){
 return e.SelectMany(x => x );
}

The purpose of this function is to flatten a group of IEnumerable<IEnumerable<T>> into an IEnumerable<T>. The returned data will preserve the original order.

like image 146
JaredPar Avatar answered Oct 11 '22 06:10

JaredPar


Further to JaredPar's (correct) answer - also query syntax:

var all = from inner in outer
          from item in inner
          select item;
like image 28
Marc Gravell Avatar answered Oct 11 '22 06:10

Marc Gravell