如何排序嵌套字典.net c#
本文关键字:嵌套 字典 net 排序 何排序 | 更新日期: 2023-09-27 18:18:11
using System;
using System.Collections.Generic;
using System.Linq;
class Dictionary
{
static void Main()
{
Dictionary<string,Dictionary<string,float>> dict = new Dictionary<string, Dictionary<string, float>>();
String input = Console.ReadLine();
String[] data = input.Split();
string name = "";
float result = 0;
while (data[0] != "end")
{
if (data.Length == 1)
{
name = data[0];
dict.Add(name, new Dictionary<string, float>());
}
else if (data.Length > 1)
{
result = float.Parse(data[1]);
dict[name].Add(data[0], result);
}
data = Console.ReadLine().Split(); // input
}
// var dic2 = from x in dict
// orderby x.Key
// select x;
foreach (var item in dict)
{
Console.WriteLine("Country: {0}", item.Key);
string temp = item.Key;
foreach (var element in dict[temp])
{
Console.WriteLine("City: {0}, population: {1}", element.Key, element.Value);
}
}
}
}
我有一个字典键->国家,嵌套->字典键->城市,值->我想要的人口
在内部"嵌套"字典中对国家和人口进行排序。我花了几个小时寻找正确的答案,但没有找到我的问题解决了。我能找到这些信息,但找不到分类的方法。感谢任何帮助。PS:我现在正在学习字典。谢谢。
你可以使用SortedDictionary作为你的内部字典
我假设你有一些像(数字组成)
USA
- LA : 5000000
- New York : 10000000
- Boston : 3000000
Australia
- Sydney : 4000000
- Canberra : 500000
Canada
- Ontario : 1000000
- Toronto : 2000000
而你希望它是
Australia
- Canberra : 500000
- Sydney : 4000000
Canada
- Ontario : 1000000
- Toronto : 2000000
USA
- Boston : 3000000
- LA : 5000000
- New York : 10000000
首先,你不能对字典进行排序。但你确实有一些选择。您可以在指定比较器的地方使用SortedDictionary
。或者您可以将元素输出到KeyValuePairs
列表并对其进行排序。