自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

如何按 Value 對 Dictionary 進(jìn)行排序?

開發(fā) 前端
我需要對 dictionary 中的value進(jìn)行排序,這個dictionary是由key和value組成,舉個例子:我有一個 word 和相應(yīng)單詞 頻次 的hash對,現(xiàn)在我想按照 頻次 對 word 進(jìn)行排序。

 [[421319]]

本文轉(zhuǎn)載自微信公眾號「NET技術(shù)問答」,作者Stackoverflow。轉(zhuǎn)載本文請聯(lián)系NET技術(shù)問答公眾號。

咨詢區(qū)

  • Kalid:

我需要對 dictionary 中的value進(jìn)行排序,這個dictionary是由key和value組成,舉個例子:我有一個 word 和相應(yīng)單詞 頻次 的hash對,現(xiàn)在我想按照 頻次 對 word 進(jìn)行排序。

我想使用 SortList 實(shí)現(xiàn),但它只能實(shí)現(xiàn)單值排序,比如存放 頻次,但這樣我還要通過它反找 word,貌似不好實(shí)現(xiàn),在 .NET 框架中還有一個 SortDictionary ,我發(fā)現(xiàn)它只能按照 key 排序,要想硬實(shí)現(xiàn)還得定義一些自定義類。

請問是否有更簡潔的方式實(shí)現(xiàn)?

回答區(qū)

  • cardden:

要說簡潔的方法,可以用 Linq 實(shí)現(xiàn),參考如下代碼:

  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;

其實(shí)用 Linq 可以給我們帶來非常大的靈活性,它可以獲取 top10, top20,還有 top10% 等等。

  • Michael Stum:

如果抽象起來看,除了對 dictionary 進(jìn)行整體遍歷查看每個item之外,你沒有任何其他辦法,我的做法是將 dictionary 轉(zhuǎn)成 List 然后使用自帶的 Sort 方法進(jìn)行排序,參考如下代碼:

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

點(diǎn)評區(qū)

要說簡單快捷的方式,我覺得除 Linq 之外應(yīng)該也沒啥好方法了,如果要我實(shí)現(xiàn),我大概會這么寫。

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

 

責(zé)任編輯:武曉燕 來源: NET技術(shù)問答
相關(guān)推薦

2020-11-25 12:20:08

Linuxps命令

2016-12-01 15:43:41

Linuxls命令

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性能優(yōu)化

2009-07-02 10:03:02

DataView排序

2010-05-11 08:58:22

mysql表字段

2010-01-20 17:48:07

C++ 函數(shù)重載

2021-09-27 16:39:10

PythonGif壓縮

2022-04-26 05:55:13

容器K8s管理debug問題

2014-05-14 00:50:18

JoyentNode

2011-04-13 08:49:33

DataSet強(qiáng)類型化

2021-05-06 09:33:32

OperatorKubernetes開源

2013-05-24 09:25:27

2020-12-22 21:57:39

人臉識別AI人工智能

2010-02-02 14:11:14

Python 進(jìn)行編程

2010-05-25 10:11:06

ubuntu Grub
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號