我经常需要根据值对字典(由键和值组成)进行排序。例如,我有一个单词和相应频率的散列,我想按频率排序。
有一个SortedList,它适用于单个值(比如频率),我想把它映射回单词。
SortedDictionary按键排序,而不是按值。有些人求助于自定义课程,但有没有更干净的方法呢?
我经常需要根据值对字典(由键和值组成)进行排序。例如,我有一个单词和相应频率的散列,我想按频率排序。
有一个SortedList,它适用于单个值(比如频率),我想把它映射回单词。
SortedDictionary按键排序,而不是按值。有些人求助于自定义课程,但有没有更干净的方法呢?
当前回答
环顾四周,使用一些c# 3.0特性,我们可以这样做:
foreach (KeyValuePair<string,int> item in keywordCounts.OrderBy(key=> key.Value))
{
// do something with item.Key and item.Value
}
这是我见过的最干净的方法,类似于Ruby处理散列的方法。
其他回答
字典根据定义是一种无序的关联结构,仅以可哈希的方式包含值和键。换句话说,没有一种可预见的方式来排序一本字典。
作为参考,请阅读这篇来自python语言的文章。
链接 Python数据结构
假设我们有一个这样的字典:
Dictionary<int, int> dict = new Dictionary<int, int>();
dict.Add(21,1041);
dict.Add(213, 1021);
dict.Add(45, 1081);
dict.Add(54, 1091);
dict.Add(3425, 1061);
dict.Add(768, 1011);
你可以使用临时字典来存储值:
Dictionary<int, int> dctTemp = new Dictionary<int, int>();
foreach (KeyValuePair<int, int> pair in dict.OrderBy(key => key.Value))
{
dctTemp.Add(pair.Key, pair.Value);
}
在较高的层次上,您别无选择,只能遍历整个Dictionary并查看每个值。
也许这有帮助: http://bytes.com/forum/thread563638.html 复制/粘贴自John Timney:
Dictionary<string, string> s = new Dictionary<string, string>();
s.Add("1", "a Item");
s.Add("2", "c Item");
s.Add("3", "b Item");
List<KeyValuePair<string, string>> myList = new List<KeyValuePair<string, string>>(s);
myList.Sort(
delegate(KeyValuePair<string, string> firstPair,
KeyValuePair<string, string> nextPair)
{
return firstPair.Value.CompareTo(nextPair.Value);
}
);
使用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;
这也为你提供了很大的灵活性,你可以选择前10%,20 - 10%等等。或者,如果您正在使用词频索引进行提前输入,您还可以包括StartsWith子句。
反正你也不可能对字典进行排序。它们实际上并不是有序的。字典的保证是键和值集合是可迭代的,值可以通过索引或键检索,但不保证任何特定的顺序。因此,您需要将名称值对放入一个列表中。