【发布时间】:2018-11-23 00:44:07
【问题描述】:
好的,我想在这里完成的是我有一个字典,其中包含如下所示的数据:
未分类:
US ( total population: 9 )
-New York - 4
-Miami - 5
Spain ( total population: 4 )
-Madrid - 3
-Barcelona - 1
France ( total population: 7 )
-Paris - 7
我需要按人口最多的国家对字典进行排序,然后按人口最多的每个城市对字典进行排序,所以它看起来像这样:
排序:
US ( total population: 9 )
-Miami - 5
-New York - 4
France ( total population: 7 )
-Paris - 7
Spain ( total population: 4 )
-Madrid - 3
-Barcelona - 1
我有:
var worldPopulation = new Dictionary<string, Dictionary<string, long>>();
我已经使用这行代码对国家进行了排序:
worldPopulation = worldPopulation.OrderByDescending(x => x.Value.Values.Sum()).ToDictionary(x => x.Key, x => x.Value);
但我正在努力寻找一种解决方案来对包含国家/地区的嵌套字典进行排序。
我正在尝试使用单个 linq 语句来执行此操作,但如果它不可能,也将不胜感激 foreach 解决方案。谢谢!
编辑:
@J_L 的解决方案正是我想要的:
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 的解决方案也让它发挥了作用:
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)));
我知道你们中的一些人告诉我要使用不同的方法,所以我会按照你们中的一些人的建议尝试使用列表。我也学到了一些新东西,所以感谢大家的帮助。
【问题讨论】:
-
字典中的项目顺序没有意义。访问是通过密钥完成的。如果您希望对其进行排序,可以考虑使用不同的数据结构。例如,不要调用
.ToDictionary,而是将其存储在一个元组列表中。也看看How do you sort a dictionary by value? -
你使用了错误的集合字典没有排序你想要一个 SortedList
-
我只想在这里上课。
标签: c# sorting dictionary