-2

I want to sort a dictonary by its key but all the other answers involved making a list and adding it to that. It there a way to sort the dictonary itself and move the keys along with the corresponding value? Example:

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

then make the dictonary equal

0, 1

1, 2

2, 7

4, 0

5, 4

7, 9

ScottMcGready
  • 1,612
  • 2
  • 24
  • 33

1 Answers1

0

It depends what you mean by the dictionary being "equal" to what you said. If it's just on output then

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

will show

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

but

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

will show

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

The question of whether to choose SortedList or SortedDictionary is answered here.

Community
  • 1
  • 1
ClickRick
  • 1,553
  • 2
  • 17
  • 37