你如何按值对字典进行排序? [英] 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.
有一个 SortedList
适合单个值(比如频率),我想将它映射回单词.
There is a SortedList
which is good for a single value (say frequency), that I want to map it back to the word.
SortedDictionary 按键而非值排序.有些人求助于自定义类,但有更简洁的方法吗?
SortedDictionary orders by key, not value. Some resort to a custom class, but is there a cleaner way?
推荐答案
使用:
using System.Linq.Enumerable;
...
List<KeyValuePair<string, string>> myList = aDictionary.ToList();
myList.Sort(
delegate(KeyValuePair<string, string> pair1,
KeyValuePair<string, string> pair2)
{
return pair1.Value.CompareTo(pair2.Value);
}
);
由于您的目标是 .NET 2.0 或更高版本,您可以将其简化为 lambda 语法——它等效,但更短.如果您的目标是 .NET 2.0,则只有在使用 Visual Studio 2008(或更高版本)的编译器时才能使用此语法.
Since you're targeting .NET 2.0 or above, you can simplify this into lambda syntax -- it's equivalent, but shorter. If you're targeting .NET 2.0 you can only use this syntax if you're using the compiler from Visual Studio 2008 (or above).
var myList = aDictionary.ToList();
myList.Sort((pair1,pair2) => pair1.Value.CompareTo(pair2.Value));
这篇关于你如何按值对字典进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!