如何按 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源创计划”,欢迎正在阅读的你也加入,一起分享。

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