我有一個包含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);
}
在調試,什麼類型的排序? – jbg
那麼到目前爲止'排序'查詢是排序的結果wordDictionary – user9993
我不認爲有可能排序一個只讀字典(普通字典不保證順序,而迭代它)。您可能最有可能返回鍵值對的只讀列表。 – Ideae