反向排序字典?

时间:2010-05-06 21:24:49

标签: c#

我有SortedDictionary定义如下:

SortedDictionary<TPriority, Queue<TValue>> dict;

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

3 个答案:

答案 0 :(得分: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); }
}

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

var dict = new SortedDictionary<TPriority, Queue<TValue>>(
                 new ReverseComparer<TPriority>());

答案 1 :(得分:1)

如果你可以使用LINQ,你可以这样做:

dict.Keys.Reverse();

这会以相反的顺序生成集合的键。

编辑:SortedDictionary类在构造时被赋予IComparer<T>,并且在事后不能更改。但是,您可以从原始文件中创建新的SortedDictionary<T>

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

答案 2 :(得分:1)

我最后只是将它添加到我的班级,因为它是最短最简单的:

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

然后像这样初始化dict

dict = new SortedDictionary<TPriority, Queue<TValue>>(new ReverseComparer());