你如何排序值字典吗? [英] How do you sort a dictionary by value?
问题描述
我经常要排序的字典,包括键和放大器;值,按值。例如,我有话和相应频率的哈希,我想通过频率来订购。
有一个排序列表
这是很好的一个值(说频率),我想它映射回字。
SortedDictionary 通过键,而不是价值的订单。有些再打自定义类,但有一个更清洁的方式?
使用System.Linq.Enumerable;
...
清单< KeyValuePair<字符串,字符串>> myList中= aDictionary.ToList();myList.Sort(
委托(KeyValuePair<字符串,字符串> pair1,
KeyValuePair<字符串,字符串> pair2)
{
返回pair1.Value.CompareTo(pair2.Value);
}
);
由于您的目标.NET 2.0或更高版本,可以简化到这一lambda语法 - 这是等价的,但更短。如果你的目标.NET 2.0中,您只能使用此语法,如果你正在使用的编译器VS2008(或以上)。
VAR myList中= aDictionary.ToList();myList.Sort((pair1,pair2)= GT; pair1.Value.CompareTo(pair2.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.
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);
}
);
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 vs2008 (or above).
var myList = aDictionary.ToList();
myList.Sort((pair1,pair2) => pair1.Value.CompareTo(pair2.Value));
这篇关于你如何排序值字典吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!