0

I have a Dictionary that I want to sort by its keys.

var dict = new Dictionary<int, string>(){
    {1, "a"},
    {3, "c"},
    {2, "b"}
};

Converting it to a SortedDictionary alone doesn't work because I need the keys to be descending in value:

var sortedDict = new SortedDictionary<int, string>(dict);
foreach (var k in sortedDict)
{
    Console.WriteLine(k);
}

// Result:
[1, a]
[2, b]
[3, c]

// Desired result:
[3, c]
[2, b]
[1, a]

Is there any way to sort the Dictionary with a custom sorting option (like a lambda)?

max
  • 147
  • 1
  • 7

1 Answers1

2
var dict = new Dictionary<int, string>(){
  {1, "a"},
  {3, "c"},
  {2, "b"}
};

foreach (var k in dict.OrderByDescending(x => x.Key))
{
   Console.WriteLine(k);
}
Pinx0
  • 1,248
  • 17
  • 28