Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SortedDictionary in reverse order of keys [duplicate]

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.

like image 590
Adam Levitt Avatar asked Nov 10 '12 15:11

Adam Levitt


1 Answers

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.

like image 127
Jeppe Stig Nielsen Avatar answered Sep 28 '22 08:09

Jeppe Stig Nielsen