Reputation: 3954
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!
Upvotes: 61
Views: 51759
Reputation: 1500385
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.
Upvotes: 114
Reputation: 44288
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.
Upvotes: 12
Reputation: 2051
Assuming you have an instance called dict:
dict.SelectMany(pair => pair.Value.Select(str => str));
Upvotes: 2
Reputation: 39013
You should try something like this:
dict.Values.Aggregate(new List<String>(), (a, b) => a.Concat(b));
Upvotes: 1
Reputation: 30580
SelectMany
is the easiest way to flatten things:
Dictionary.Values.SelectMany(x => x).ToList()
Upvotes: 8