2015-01-11 50 views
1

我有一個包含Dictionary<string, uint>的方法。該方法返回從Dictionary<string, uint>創建的ReadOnlyDictionary<string, uint>返回按值排序的ReadOnlyDictionary

我希望返回的字典排序而不是按鍵。我已經在網上搜索,發現了一些LINQ的排序由值:

var sorted = from entry in _wordDictionary orderby entry.Value descending select entry; 

不過,我不知道如何再結合我正在返回ReadOnlyDictionary<string, uint>使用。

這裏是我的代碼:

public static ReadOnlyDictionary<string, uint> GetWordCountDictionary(string stringToCount) 
{ 
    Dictionary<string, uint> wordDictionary = new Dictionary<string, uint>(); 

    //Rest of the method here that is not relevant 

    var sorted = from entry in wordDictionary orderby entry.Value descending select entry; 

    ReadOnlyDictionary<string, uint> result = new ReadOnlyDictionary<string, uint>(wordDictionary); 

    return result; 
} 

正如代碼目前維持,這將返回未排序的字典,但是,如果我不是這樣做:

ReadOnlyDictionary<string, uint> result = new ReadOnlyDictionary<string, uint>(sorted); 

我得到的錯誤:

The best overloaded method match for 'System.Collections.ObjectModel.ReadOnlyDictionary<string,uint>.ReadOnlyDictionary(System.Collections.Generic.IDictionary<string,uint>)' has some invalid arguments 

Argument 1: cannot convert from 'System.Linq.IOrderedEnumerable<System.Collections.Generic.KeyValuePair<string,uint>>' to 'System.Collections.Generic.IDictionary<string,uint>' 

如何返回按值排序字典?

編輯

如果是相關的,這是怎麼了目前能夠遍歷結果:

var result = WordCounter.GetWordCountDictionary(myString); 

foreach (var word in result) 
{ 
    Console.WriteLine ("{0} - {1}", word.Key, word.Value); 
} 
+0

在調試,什麼類型的排序? – jbg

+0

那麼到目前爲止'排序'查詢是排序的結果wordDictionary – user9993

+0

我不認爲有可能排序一個只讀字典(普通字典不保證順序,而迭代它)。您可能最有可能返回鍵值對的只讀列表。 – Ideae

回答

1

構造函數期待一個IDictionary<string,uint>但你給它IOrderedEnumerable<KeyValuePair<string,uint>>

var result = new ReadOnlyDictionary<string, uint>(sorted.ToDictionary(x => x.Key,x => x.Value)); 
0

解決您的問題是更改行,

ReadOnlyDictionary<string, uint> result = new ReadOnlyDictionary<string, uint>(sorted); 

ReadOnlyDictionary<string, uint> result = new ReadOnlyDictionary<string, uint>(sorted.ToDictionary(t => t.Key,t => t.Value)); 
1

因爲你把排序結果到字典中,其中項目枚舉過程中返回的順序是不確定的,根據MSDN

爲目的枚舉時,字典中的每個項都被視爲代表一個值的KeyValuePair結構及其 鍵。項目返回的順序是未定義的。

我建議你,而不是一個列表返回結果:

 var sorted = (from entry in wordDictionary 
        orderby entry.Value descending 
        select entry).ToList(); 

     foreach (var word in sorted) 
     { 
      Console.WriteLine("{0} - {1}", word.Key, word.Value); 
     } 

ToList方法將導致System.Collections.Generic.List<KeyValuePair<string, uint>>