61

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!

0

5 Answers 5

114

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Cool. How does SelectMany differ from Select?
@Paul I'm so tempted to just comment saying, "it selects many", but actually that's pretty much it. If you have an enumerable (or queryable) object that when enumerated returns yet more enumerable objects, such as a list of lists or an array of hash-sets, etc, it selects the elements of those objects. So in this where values is an ICollection<List<string>> it returns an IEnumerable<string>.
@JonHanna Best to-the-point explanation of SelectMany I have ever seen. Not only brief, but something I can remember.
The problem with this is that we los the keys, I imagined something like a key/value with the keys duplicated
|
12

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.

Comments

8

SelectMany is the easiest way to flatten things:

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

Comments

2

Assuming you have an instance called dict:

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

Comments

1

You should try something like this:

dict.Values.Aggregate(new List<String>(), (a, b) => a.Concat(b));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.