反向排序字典?

mpe*_*pen 8 c#

我有这样的SortedDictionary定义:

SortedDictionary<TPriority, Queue<TValue>> dict;
Run Code Online (Sandbox Code Playgroud)

但我想以相反的顺序维护字典.我假设我需要设置Comparer,但是我用什么比较器用于通用TPriority?注意TPriority实现IComparable.

Mar*_*ell 16

您可以非常轻松地创建反向比较器:

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); }
}
Run Code Online (Sandbox Code Playgroud)

现在将其传递给字典的构造函数:

var dict = new SortedDictionary<TPriority, Queue<TValue>>(
                 new ReverseComparer<TPriority>());
Run Code Online (Sandbox Code Playgroud)