Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

c# - 你如何按价值排序字典?(How do you sort a dictionary by value?)

I often have to sort a dictionary, consisting of keys & values, by value.

(我经常需要按值排序字典,包括键和值。)

For example, I have a hash of words and respective frequencies, that I want to order by frequency.

(例如,我有一个单词和各自频率的哈希,我想按频率排序。)

There is a SortedList which is good for a single value (say frequency), that I want to map it back to the word.

(有一个SortedList适用于单个值(比如频率),我想将它映射回单词。)

SortedDictionary orders by key, not value.

(SortedDictionary按键排序 ,而不是值。)

Some resort to a custom class , but is there a cleaner way?

(有些人诉诸于自定义课程 ,但是有更清洁的方法吗?)

  ask by Kalid translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use LINQ:

(使用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;

This would also allow for great flexibility in that you can select the top 10, 20 10%, etc. Or if you are using your word frequency index for type-ahead , you could also include StartsWith clause as well.

(这也可以提供很大的灵活性,你可以选择前10个,20个10%等。或者如果你使用你的单词频率索引进行type-ahead ,你也可以包括StartsWith子句。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...