Question

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.

Was it helpful?

Solution 2

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top