对字典进行排序

本文关键字:排序 字典 | 更新日期: 2023-09-27 17:57:55

我想按关键字对dictionary进行排序,但所有其他答案都涉及到制作一个列表并将其添加到其中。有没有一种方法可以对dictionary本身进行排序,并将关键字与相应的值一起移动?示例:

Dictonary<int, int> dict = new Dictionary<int, int>();
dict.Add(0, 1);
dict.Add(5, 4);
dict.Add(2, 7);
dict.Add(7, 9);
dict.Add(1, 2);
dict.Add(4, 0);

然后使dictionary等于

0,1

1,2

2,7

4,0

5,4

7,9

对字典进行排序

这取决于字典与你所说的"相等"是什么意思。如果只是输出,则

        foreach (var entry in dict)
            Console.WriteLine(entry);

将显示

[0, 1]
[5, 4]
[2, 7]
[7, 9]
[1, 2]
[4, 0]

但是

        foreach (var entry in new SortedDictionary<int, int>(dict)) // or SortedList
            Console.WriteLine(entry);

将显示

[0, 1]
[1, 2]
[2, 7]
[4, 0]
[5, 4]
[7, 9]

这里回答了是选择SortedList还是SortedDictionary的问题。