Flatten a C# Dictionary of Lists with 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!


Solution 1:

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.

Solution 2:

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.

Solution 3:

SelectMany is the easiest way to flatten things:

Dictionary.Values.SelectMany(x => x).ToList()

Solution 4:

Assuming you have an instance called dict:

dict.SelectMany(pair => pair.Value.Select(str => str));