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!
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.
ICollection<List<string>> it returns an IEnumerable<string>.SelectMany is the easiest way to flatten things:
Dictionary.Values.SelectMany(x => x).ToList()