Okay, what I am trying to accomplish here is I have a dictionary with data that looks like this:
Unsorted:
US ( total population: 9 )
-New York - 4
-Miami - 5
Spain ( total population: 4 )
-Madrid - 3
-Barcelona - 1
France ( total population: 7 )
-Paris - 7
I need to sort the dictionaries by Country with largest population and then every city by largest population so it looks something like this:
Sorted:
US ( total population: 9 )
-Miami - 5
-New York - 4
France ( total population: 7 )
-Paris - 7
Spain ( total population: 4 )
-Madrid - 3
-Barcelona - 1
I have:
var worldPopulation = new Dictionary<string, Dictionary<string, long>>();
I already sorted the countries using this line of code:
worldPopulation = worldPopulation.OrderByDescending(x => x.Value.Values.Sum()).ToDictionary(x => x.Key, x => x.Value);
But I am struggling to find a solution for sorting the nested dictionary with the countries.
I am trying to do this with a single linq statement, but if its not possible a foreach solution would also be appreciated. Thanks!
EDIT:
@J_L's solution was exactly what I was looking for:
worldPopulation = worldPopulation.OrderByDescending(x => x.Value.Values.Sum()).ToDictionary(x => x.Key, x => x.Value.OrderByDescending(y => y.Value).ToDictionary(y => y.Key, y => y.Value));
@Lucifer's solution also made it work:
var worldPopulationSorted = new Dictionary<string, Dictionary<string, long>>();
worldPopulation.OrderByDescending(dic => dic.Value.Values.Sum()).ToList().ForEach(x => worldPopulationSorted.Add(x.Key, x.Value.OrderByDescending(y => y.Value).ToDictionary(y => y.Key, y => y.Value)));
I understand that some of you are telling me to use a different approach, so will try using lists as some of you suggested. I also learned some new things, so thanks to everyone for the help.