2015-10-18 107 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有錯誤,但你有想法 –