如何按 value 對 dictionary 進行排序?

諮詢區

  • Kalid

我需要對 dictionary 中的value進行排序,這個dictionary是由keyvalue組成,舉個例子:我有一個 word 和相應單詞 頻次 的hash對,現在我想按照 頻次 對 word 進行排序。

我想使用 SortList 實現,但它只能實現單值排序,比如存放 頻次,但這樣我還要通過它反找 word,貌似不好實現,在 .NET 框架中還有一個 SortDictionary ,我發現它只能按照 key 排序,要想硬實現還得定義一些自定義類。

請問是否有更簡潔的方式實現?

回答區

  • cardden

要說簡潔的方法,可以用 Linq 實現,參考如下代碼:


Dictionary<stringint> myDict = new Dictionary<stringint>();
myDict.Add("one"1);
myDict.Add("four"4);
myDict.Add("two"2);
myDict.Add("three"3);

var sortedDict = from entry in myDict orderby entry.Value ascending select entry;

其實用 Linq 可以給我們帶來非常大的靈活性,它可以獲取 top10, top20,還有 top10% 等等。

  • Michael Stum

如果抽象起來看,除了對 dictionary 進行整體遍歷查看每個item之外,你沒有任何其他辦法,我的做法是將 dictionary 轉成 List<KeyValuePari> 然後使用自帶的 Sort 方法進行排序,參考如下代碼:


Dictionary<stringstring> s = new Dictionary<stringstring>();
s.Add("1""a Item");
s.Add("2""c Item");
s.Add("3""b Item");

List<KeyValuePair<stringstring>> myList = new List<KeyValuePair<stringstring>>(s);
myList.Sort(
    delegate(KeyValuePair<stringstring> firstPair,
    KeyValuePair<stringstring> nextPair)
    {
        return firstPair.Value.CompareTo(nextPair.Value);
    }
);

點評區

要說簡單快捷的方式,我覺得除 Linq 之外應該也沒啥好方法了,如果要我實現,我大概會這麼寫。


var ordered = dict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

本文分享自微信公衆號 - 一線碼農聊技術(dotnetfly)。
如有侵權,請聯繫 [email protected] 刪除。
本文參與“OSC源創計劃”,歡迎正在閱讀的你也加入,一起分享。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章