2015-10-18 104 views
1
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); 
      } 
     } 
    } 
} 

我有一个字典密钥 - >国家,nested->词典密钥 - >城市价值 - >人口,我想
排序的国家和人民内部的“嵌套”字典。我 花了几个小时寻找正确的答案,但找不到解决我的问题的 。我能够对信息进行foreach,但找不到排序方式。任何帮助赞赏。 PS:我现在只学习字典。 谢谢。如何排序嵌套字典.net C#?

+0

您能举一个例子说明您如何期望生成的排序字典的结构? – Dietz

回答

1

我假设你有这样的事情(由数字)

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 

首先,你不能排序的字典。但你有一些选择。 You can use a SortedDictionary where you specify the comparer。 或者您可以输出元素到KeyValuePairs的列表中并对其进行排序。

+0

是的,我想要完全按照上面的示例进行操作。如果它是一个带有键和值的字典,我可以用linq对它进行排序,我的意思是将元素排序到另一个KeyValuePair集合// var dic2 = from x in dict // orderby x.Key // select x;但与嵌套字典它没有工作。 –

+0

那么,正如我所说,你有两个选择: –

+0

如果你想要的元素总是排序,你可以将'dict'改成'SortedDictionary >'。如果你只是想在给定的时间输出排序的元素,你可以做类似于 'var sorted = dict.ToList()。OrderBy(x => x.Key).Select(country => new KeyValuePair < string,List >>(country.Key,country.Value.ToList()。OrderBy(x => x.Value))' 代码不在我头顶,所以prob有错误,但你有想法 –