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
.
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>());
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 ) );
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With