【问题标题】:Sorted dictionaries排序的字典
【发布时间】:2014-02-23 15:43:04
【问题描述】:

我正在寻找一些关于排序字典的信息,因为我以前从未详细使用过它们。

根据我对它们的了解,它们按照放置在其中的键值对自身进行排序。那是对的吗?另外,字典是否会根据读入的值不断地自动排序?

如果是这样,有没有一种方法可以更改它,以便字典通过与键关联的值对自身进行排序。例如,我有一个排序字典,其中包含以下内容:

Key: 4  Value: 40 
Key: 1  Value: 290 
Key: 86  Value: 7 

排序后的字典会这样排序:

Key: 1  Value: 290 
Key: 4  Value: 40 
Key: 86  Value: 7 

但我希望它执行以下操作:

Key: 86  Value: 7 
Key: 4  Value: 40 
Key: 1  Value: 290 

最后,我将如何访问此排序的第一点和第二点,以便我可以将它们分配给其他东西?

【问题讨论】:

标签: c# sorting dictionary sorteddictionary


【解决方案1】:

默认情况下,SortedDictionary<TKey, TValue> 基于Key 执行Sorting,而不是基于Value

但如果您想根据Value 进行排序,您可以使用 LINQ OrderBy() 方法,如下所示:

来自 MSDN:SortedDictionary

表示按键排序的键/值对的集合。

试试这个:

var SortedByValueDict = dict.OrderBy(item => item.Value);

完整代码:

class Program
{
static void Main(string[] args)
{
    SortedDictionary<int, int> dict = new SortedDictionary<int, int>();
    dict.Add(4, 40);
    dict.Add(1, 290);
    dict.Add(86, 7);

    Console.WriteLine("Sorted Dictionary Items sorted by Key");
    foreach (var v in dict)
    {
    Console.WriteLine("Key = {0} and Value = {1}", v.Key, v.Value);
    }

    Console.WriteLine("------------------------\n");
    Console.WriteLine("Sorted Dictionary Items sorted by Value");
    var SortedByValueDict = dict.OrderBy(item => item.Value);

    foreach (var v in SortedByValueDict)
    {
    Console.WriteLine("Key = {0} and Value = {1}", v.Key, v.Value);
    }
}
}

输出:

Sorted Dictionary Items sorted by Key
Key = 1 and Value = 290
Key = 4 and Value = 40
Key = 86 and Value = 7
------------------------

Sorted Dictionary Items sorted by Value
Key = 86 and Value = 7
Key = 4 and Value = 40
Key = 1 and Value = 290

【讨论】:

    猜你喜欢
    • 2013-05-01
    • 1970-01-01
    • 2011-05-06
    • 2012-06-16
    • 1970-01-01
    • 2018-01-02
    • 2011-05-18
    • 1970-01-01
    • 2010-12-23
    相关资源
    最近更新 更多