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!
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.
It can take anywhere from 6-8 weeks for your uterus to go back to its normal size.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With