Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join together all the elements in an IEnumerable of IEnumerables?

Just in case you're wondering how this came up, I'm working with some resultsets from Entity Framework.

I have an object that is an IEnumerable<IEnumerable<string>>; basically, a list of lists of strings.

I want to merge all the lists of strings into one big list of strings.

What is the best way to do this in C#.net?

like image 410
Vivian River Avatar asked Aug 14 '12 18:08

Vivian River


1 Answers

Use the LINQ SelectMany method:

IEnumerable<IEnumerable<string>> myOuterList = // some IEnumerable<IEnumerable<string>>...
IEnumerable<String> allMyStrings = myOuterList.SelectMany(sl => sl);

To be very clear about what's going on here (since I hate the thought of people thinking this is some kind of sorcery, and I feel bad that some other folks deleted the same answer):

SelectMany is an extension method ( a static method that through syntactic sugar looks like an instance method on a specific type) on IEnumerable<T>. It takes your original enumeration of enumerations and a function for converting each item of that into a enumeration.

Because the items are already enumerations, the conversion function is simple- just return the input (sl => sl means "take a paremeter named sl and return it"). SelectMany then provides an enumeration over each of these in turn, resulting in your "flattened" list..

like image 94
Chris Shain Avatar answered Sep 20 '22 05:09

Chris Shain