如何按 Value 对 Dictionary 进行排序?

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

 [[421319]]

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

咨询区

  • Kalid:

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

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

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

回答区

  • cardden:

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

  1. Dictionary<string, int> myDict = new Dictionary<string, int>(); 
  2. myDict.Add("one", 1); 
  3. myDict.Add("four", 4); 
  4. myDict.Add("two", 2); 
  5. myDict.Add("three", 3); 
  6.  
  7. 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 方法进行排序,参考如下代码:

  1. Dictionary<string, string> s = new Dictionary<string, string>(); 
  2. s.Add("1""a Item"); 
  3. s.Add("2""c Item"); 
  4. s.Add("3""b Item"); 
  5.  
  6. List<KeyValuePair<string, string>> myList = new List<KeyValuePair<string, string>>(s); 
  7. myList.Sort( 
  8.     delegate(KeyValuePair<string, string> firstPair, 
  9.     KeyValuePair<string, string> nextPair) 
  10.     { 
  11.         return firstPair.Value.CompareTo(nextPair.Value); 
  12.     } 
  13. ); 

点评区

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

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

 

责任编辑:武晓燕 来源: NET技术问答
相关推荐

2016-12-01 15:43:41

Linuxls命令

2020-11-25 12:20:08

Linuxps命令

2021-11-08 10:58:08

变量依赖图排序

2011-07-13 13:39:46

CHARINDEXSqlServer

2011-03-02 10:33:33

终端虚拟化

2010-07-21 10:36:18

SQL Server

2011-01-20 10:33:30

Postfix

2023-01-30 08:30:09

Tomcat性能优化

2009-07-02 10:03:02

DataView排序

2010-05-11 08:58:22

mysql表字段

2010-01-20 17:48:07

C++ 函数重载

2021-09-27 16:39:10

PythonGif压缩

2022-04-26 05:55:13

容器K8s管理debug问题

2014-05-14 00:50:18

JoyentNode

2013-05-24 09:25:27

2020-12-22 21:57:39

人脸识别AI人工智能

2011-04-13 08:49:33

DataSet强类型化

2021-05-06 09:33:32

OperatorKubernetes开源

2010-02-02 14:11:14

Python 进行编程

2010-05-25 10:11:06

ubuntu Grub
点赞
收藏

51CTO技术栈公众号