SortedDictionary in reverse order of keys

Adam Levitt picture Adam Levitt · Nov 10, 2012 · Viewed 7.8k times · Source

I have the following dictionary:

SortedDictionary<int, string> dictionary = new SortedDictionary<int, string>();
dictionary.add(2007, "test1");
dictionary.add(2008, "test2");
dictionary.add(2009, "test3");
dictionary.add(2010, "test4");
dictionary.add(2011, "test5");
dictionary.add(2012, "test6");

I'd like to reverse the order of the elements so that when I display the items on the screen, I can start with 2012. I'd like to reassign the reversed dictionary back to the variable dictionary if possible.

I tried dictionary.Reverse but that doesn't seem to be working as easily as I thought.

Answer

Jeppe Stig Nielsen picture Jeppe Stig Nielsen · Nov 10, 2012

If you're using the newest version of the framework, .NET 4.5 (Visual Studio 2012), you can do it very easily with Comparer<>.Create. It's like this:

var dictionary =
  new SortedDictionary<int, string>(Comparer<int>.Create((x, y) => y.CompareTo(x)));

Note the order of x and y in the lambda.