Search code examples
c#linqreversesorteddictionary

SortedDictionary in reverse order of keys


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.


Solution

  • You can give SortedDictionary an IComparer<TKey> on construction. You just need to provide one which reverses the order. For example:

    public sealed class ReverseComparer<T> : IComparer<T>
    {
        private readonly IComparer<T> original;
    
        public ReverseComparer(IComparer<T> original)
        {
            // TODO: Validation
            this.original = original;
        }
    
        public int Compare(T left, T right)
        {
            return original.Compare(right, left);
        }
    }
    

    Then:

    var dictionary = new SortedDictionary<int, string>(
           new ReverseComparer<int>(Comparer<int>.Default));