如何按 Value 对 Dictionary 进行排序?

 

本文转载自微信公众号「NET技术问答」,何按作者Stackoverflow。进行转载本文请联系NET技术问答公众号。排序

咨询区

Kalid:

我需要对 dictionary 中的何按value进行排序,这个dictionary是进行由key和value组成,举个例子:我有一个 word 和相应单词 频次 的排序hash对,现在我想按照 频次 对 word 进行排序。何按

我想使用 SortList 实现,进行但它只能实现单值排序,排序比如存放 频次,云南idc服务商何按但这样我还要通过它反找 word,进行貌似不好实现,排序在 .NET 框架中还有一个 SortDictionary ,何按我发现它只能按照 key 排序,要想硬实现还得定义一些自定义类。进行

请问是排序否有更简洁的方式实现?

回答区

cardden:

要说简洁的方法,可以用 Linq 实现,参考如下代码:

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;

其实用 Linq 可以给我们带来非常大的灵活性,它可以获取 top10, top20,还有 top10% 等等。服务器托管

Michael Stum:

如果抽象起来看,除了对 dictionary 进行整体遍历查看每个item之外,你没有任何其他办法,我的做法是将 dictionary 转成 List 然后使用自带的 Sort 方法进行排序,参考如下代码:

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);     } ); 

点评区

要说简单快捷的方式,我觉得除 Linq 之外应该也没啥好方法了,如果要我实现,我大概会这么写。亿华云计算

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

系统运维
上一篇:域名和网址一样吗?域名和网址有什么区别?
下一篇:换新域名(重新来过)