我经常需要根据值对字典(由键和值组成)进行排序。例如,我有一个单词和相应频率的散列,我想按频率排序。

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

SortedDictionary按键排序,而不是按值。有些人求助于自定义课程,但有没有更干净的方法呢?


当前回答

你可以用:

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

其他回答

或者为了好玩,你可以使用一些LINQ扩展的优点:

var dictionary = new Dictionary<string, int> { { "c", 3 }, { "a", 1 }, { "b", 2 } };
dictionary.OrderBy(x => x.Value)
  .ForEach(x => Console.WriteLine("{0}={1}", x.Key,x.Value));

假设我们有一个这样的字典:

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

字典根据定义是一种无序的关联结构,仅以可哈希的方式包含值和键。换句话说,没有一种可预见的方式来排序一本字典。

作为参考,请阅读这篇来自python语言的文章。

链接 Python数据结构

反正你也不可能对字典进行排序。它们实际上并不是有序的。字典的保证是键和值集合是可迭代的,值可以通过索引或键检索,但不保证任何特定的顺序。因此,您需要将名称值对放入一个列表中。

在较高的层次上,您别无选择,只能遍历整个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);
    }
);