LINQ: Flatten a List of Lists

Today I needed to flatten a list of lists and really didn’t want write out a nested loop to iterate through each element in each list. After some searching I found that LINQ provides a very elegant solution to this problem. LINQ is a powerful set of extensions that were added to the .NET Framework that allows you to query and manipulate sets of data. The SelectMany extension method solves this problem very easily as shown below.

List<List<string>> listOfLists = new List<List<string>>();
listOfLists.Add(new List<string>() { "a", "b", "c" });
listOfLists.Add(new List<string>() { "d", "e", "f" });
listOfLists.Add(new List<string>() { "g", "h", "i" });

var flattenedList = listOfLists.SelectMany(x => x);

foreach (string s in flattenedList)
     Console.Write(s + " ");

// Output
// -----
// a b c d e f g h i

Justin Etheridge has a great blog post with awesome diagrams of how the SelectMany extension method works. Check it out for more information.

Posted in LINQ. Tags: , . 3 Comments »

3 Responses to “LINQ: Flatten a List of Lists”

  1. Skyler Says:

    nice. i gotta pick up some .net!

  2. LINQ: Selecting Multiple Properties from a List of Objects « Nick Olsen's Programming Tips Says:

    […] a previous post I discussed how to use LINQ to flatten a list of lists. Yesterday and ran across a slightly […]

  3. codecontemplator Says:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: