Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten a C# Dictionary of Lists with Linq

Tags:

c#

linq

I have a Dictionary in C#:

Dictionary<string, List<string>> 

How can I use Linq to flatten this into one List<string> that contains all of the lists in the Dictionary?

Thanks!

like image 755
Paul Avatar asked Feb 23 '12 20:02

Paul


People also ask

Can you flatten AC section belly?

While diet and exercise can help women lose excess fat after pregnancy, a healthy lifestyle can't make a c-section scar and bulge go away. Some women may find their c-shelf sticks around for years, while others may notice the area gradually flattens over time.

How long does it take for stomach to flatten after C-section?

It can take anywhere from 6-8 weeks for your uterus to go back to its normal size.


2 Answers

Very easily:

var list = dictionary.Values              // To get just the List<string>s                      .SelectMany(x => x)  // Flatten                      .ToList();           // Listify 

Here the SelectMany call takes a sequence of inputs (the lists which make the values of the dictionary) and projects each single input into another sequence of outputs - in this case "the elements of the list". It then flattens that sequence of sequences into a single sequence.

like image 180
Jon Skeet Avatar answered Oct 05 '22 04:10

Jon Skeet


as a query

var flattened = from p in dictionary                 from s in p.Value                 select s; 

or as methods...

var flattened = dictionary.SelectMany(p => p.Value); 

I like this over what others have done as I'm passing the whole dictionary into the Linq query rather than just the values.

like image 26
Keith Nicholas Avatar answered Oct 05 '22 04:10

Keith Nicholas