本文转载自微信公众号「NET 技术问答」, 作者 Stack Overflow. 转载本文请联系 NET 技术问答公众号.
咨询区
Kalid:
我需要对 dictionary 中的 value 进行排序, 这个 dictionary 是由 key 和 value 组成, 举个例子: 我有一个 Word 和相应单词 频次 的 hash 对, 现在我想按照 频次 对 Word 进行排序.
我想使用 SortList 实现, 但它只能实现单值排序, 比如存放 频次, 但这样我还要通过它反找 Word, 貌似不好实现, 在 .NET 框架中还有一个 SortDictionary , 我发现它只能按照 key 排序, 要想硬实现还得定义一些自定义类.
请问是否有更简洁的方式实现?
回答区
cardden:
要说简洁的方法, 可以用 Linq 实现, 参考如下代码:
- Dictionary myDict = new Dictionary();
- 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;
其实用 Linq 可以给我们带来非常大的灵活性, 它可以获取 top10, top20, 还有 top10% 等等.
Michael Stum:
如果抽象起来看, 除了对 dictionary 进行整体遍历查看每个 item 之外, 你没有任何其他办法, 我的做法是将 dictionary 转成 List 然后使用自带的 Sort 方法进行排序, 参考如下代码:
- Dictionary s = new Dictionary();
- s.Add("1", "a Item");
- s.Add("2", "c Item");
- s.Add("3", "b Item");
- List> myList = new List>(s);
- myList.Sort(
- delegate(KeyValuePair firstPair,
- KeyValuePair nextPair)
- {
- return firstPair.Value.CompareTo(nextPair.Value);
- }
- );
点评区
要说简单快捷的方式, 我觉得除 Linq 之外应该也没啥好方法了, 如果要我实现, 我大概会这么写.
var ordered = dict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
来源: http://developer.51cto.com/art/202109/680478.htm