如何按 Value 對(duì) Dictionary 進(jìn)行排序?
本文轉(zhuǎn)載自微信公眾號(hào)「NET技術(shù)問(wèn)答」,作者Stackoverflow。轉(zhuǎn)載本文請(qǐng)聯(lián)系NET技術(shù)問(wèn)答公眾號(hào)。
咨詢(xún)區(qū)
- Kalid:
我需要對(duì) dictionary 中的value進(jìn)行排序,這個(gè)dictionary是由key和value組成,舉個(gè)例子:我有一個(gè) word 和相應(yīng)單詞 頻次 的hash對(duì),現(xiàn)在我想按照 頻次 對(duì) word 進(jìn)行排序。
我想使用 SortList 實(shí)現(xiàn),但它只能實(shí)現(xiàn)單值排序,比如存放 頻次,但這樣我還要通過(guò)它反找 word,貌似不好實(shí)現(xiàn),在 .NET 框架中還有一個(gè) SortDictionary ,我發(fā)現(xiàn)它只能按照 key 排序,要想硬實(shí)現(xiàn)還得定義一些自定義類(lèi)。
請(qǐng)問(wèn)是否有更簡(jiǎn)潔的方式實(shí)現(xiàn)?
回答區(qū)
- cardden:
要說(shuō)簡(jiǎn)潔的方法,可以用 Linq 實(shí)現(xiàn),參考如下代碼:
- Dictionary<string, int> myDict = new Dictionary<string, int>();
- 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;
var sortedDict = from entry in myDict orderby entry.Value ascending select entry;
其實(shí)用 Linq 可以給我們帶來(lái)非常大的靈活性,它可以獲取 top10, top20,還有 top10% 等等。
- Michael Stum:
如果抽象起來(lái)看,除了對(duì) dictionary 進(jìn)行整體遍歷查看每個(gè)item之外,你沒(méi)有任何其他辦法,我的做法是將 dictionary 轉(zhuǎn)成 List
- Dictionary<string, string> s = new Dictionary<string, string>();
- s.Add("1", "a Item");
- s.Add("2", "c Item");
- s.Add("3", "b Item");
- List<KeyValuePair<string, string>> myList = new List<KeyValuePair<string, string>>(s);
- myList.Sort(
- delegate(KeyValuePair<string, string> firstPair,
- KeyValuePair<string, string> nextPair)
- {
- return firstPair.Value.CompareTo(nextPair.Value);
- }
- );
點(diǎn)評(píng)區(qū)
要說(shuō)簡(jiǎn)單快捷的方式,我覺(jué)得除 Linq 之外應(yīng)該也沒(méi)啥好方法了,如果要我實(shí)現(xiàn),我大概會(huì)這么寫(xiě)。
var ordered = dict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);