2012-02-14 57 views
5

假設我們有一個排序一個字典<INT,列表<int>>通過按鍵內部列表+值

var dictionary= new Dictionary<int, IList<int>>(); 

我要的是輸出中它的排序版本,首先下令鍵,然後按值內一個列表。

例如,

1 2, 1, 6 
5 2, 1 
2 1, 3 

變爲

1 1, 2, 6 
2 1, 3 
5 1, 2 

我試着做這裏面foreach,但顯然這是一個壞主意,改變你迭代的東西。

+1

「我想要得到的是一個有序的版本」 - _how_你想要它嗎?作爲輸出,還是作爲一個新的集合? – 2012-02-14 12:42:27

+0

編輯問題 – 2012-02-14 12:45:28

回答

10

試試這個:

// Creating test data 
    var dictionary = new Dictionary<int, IList<int>> 
    { 
     { 1, new List<int> { 2, 1, 6 } }, 
     { 5, new List<int> { 2, 1 } }, 
     { 2, new List<int> { 2, 3 } } 
    }; 

    // Ordering as requested 
    dictionary = dictionary 
     .OrderBy(d => d.Key) 
     .ToDictionary(
      d => d.Key, 
      d => (IList<int>)d.Value.OrderBy(v => v).ToList() 
     ); 

    // Displaying the results 
    foreach(var kv in dictionary) 
    { 
     Console.Write("\n{0}", kv.Key); 
     foreach (var li in kv.Value) 
     { 
      Console.Write("\t{0}", li); 
     } 
    } 
+0

這是錯誤的,原因有兩個。一,把它們放回字典中,你再次破壞他喜歡的訂單。二,你不能將'IOrderedEnumerable '投給'IList '。 – nawfal 2014-05-20 07:36:18

+0

的確,我們錯過了ToList調用。訂單保持不變。 – Schiavini 2014-05-20 08:28:15

+0

好。但是,最後通過調用「ToDictionary」,可以將項目放回無序集合中。 「工作」部分是巧合的,沒有記錄。實施可能會改變。需要記住的是**字典按定義是無序集合**。 [見](http://stackoverflow.com/questions/1453190/does-the-enumerator-of-a-dictionarytkey-tvalue-return-key-value-pairs-in-the) – nawfal 2014-05-20 08:33:10

3

A Dictionary未排序。要對字典進行排序,您可以使用OrderedDictionary

要對列表排序,你可以使用List<T>.OrderBy()

+0

這將解決只按鍵部分排序,不是嗎? – 2012-02-14 12:41:12

+1

-1:不回答問題,再讀一遍。 OP不想對字典進行排序,他/她只想輸出它。 – leppie 2012-02-14 12:41:50

+0

@leppie我再讀一遍。 OP還明確表示他/她想要一個「分類版本」。一本字典的排序版本是,好吧,去猜測。無論如何感謝downvote。 – 2012-02-14 12:46:59

0

可以遍歷字典項目和seperately排序每個列表。它看起來像這樣:

SortDictionary(dictionary);

後:

foreach (System.Collections.Generic.KeyValuePair<int,IList<int>> list in dictionary) 
     { 
      SortDictionary(list.Value) 
     } 
3

您可以使用LINQ訂購字典這樣的內容:

 var dictionary = new Dictionary<int, IList<int>>(); 
     var orderedItems = dictionary 
           .OrderBy(pair => pair.Key) 
           .Select(new { 
             Key = pair.Key, 
             Value = pair.Value.OrderBy(i => i)}); 

。當然,這是相當醜陋。在這一點上更好的選擇是使用LINQ語法

  var orderedItems =from pair in dictionary 
        orderby pair.Key 
        let values = pair.Value.OrderBy(i => i) 
        select new { Key = pair.Key, Value = values }; 

如果需要使用產生的IEnumerable列表或數組,您可以創建使用ToList或ToArray的一個。在大多數情況下,你可以直接使用IEnumerable,因爲它是

+0

失敗!去字典時,排序會丟失。 – leppie 2012-02-14 12:55:00

+0

糟糕,直接從工作代碼複製這個。現在改變它 – 2012-02-14 13:01:37

+0

顯然,不工作:p – leppie 2012-02-14 13:05:47