Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversed Sorted Dictionary?

Tags:

c#

I have a SortedDictionary as defined like this:

SortedDictionary<TPriority, Queue<TValue>> dict;

But I want to maintain the dict in reverse order. I assume I need set the Comparer, but what comparer do I use for a generic TPriority? Note that TPriority implements IComparable.

like image 822
mpen Avatar asked May 06 '10 21:05

mpen


3 Answers

You can create a reverse comparer quite easily:

public sealed class ReverseComparer<T> : IComparer<T> {
    private readonly IComparer<T> inner;
    public ReverseComparer() : this(null) { }
    public ReverseComparer(IComparer<T> inner) {
        this.inner = inner ?? Comparer<T>.Default;
    }
    int IComparer<T>.Compare(T x, T y) { return inner.Compare(y, x); }
}

Now pass that into the constructor for the dictionary:

var dict = new SortedDictionary<TPriority, Queue<TValue>>(
                 new ReverseComparer<TPriority>());
like image 189
Marc Gravell Avatar answered Oct 21 '22 08:10

Marc Gravell


If you can use LINQ, you can just do:

dict.Keys.Reverse();

This yields the keys of the collection in reverse order.

EDIT: The SortedDictionary class is assigned a IComparer<T> when it is constructed, and this cannot be changed after the fact. However, you can create a new SortedDictionary<T> from the original:

class ReverseComparer<T> : IComparer<T>  {
   private readonly m_InnerComparer = new Comparer<T>.Default;

   public ReverseComparer( IComparer<T> inner )   {
      m_InnerComparer = inner; }

   public int Compare( T first, T second )  {
       return -m_InnerComparer.Compare( first, second );  }
}

var reverseDict = new SortedDictionary<TPriority, Queue<TValue>>( dict, 
                          new ReverseComparer( Comparer<TPriority>.Default ) );
like image 35
LBushkin Avatar answered Oct 21 '22 09:10

LBushkin


I ended up just adding this to my class, as it's the shortest and simplest:

private class ReverseComparer : IComparer<TPriority>
{
    public int Compare(TPriority x, TPriority y) { return y.CompareTo(x); }
}

And then initialize the dict like so:

dict = new SortedDictionary<TPriority, Queue<TValue>>(new ReverseComparer());
like image 25
mpen Avatar answered Oct 21 '22 09:10

mpen