比较SortedDictionary的键类型

时间:2012-07-05 08:33:33

标签: c# types dictionary comparator

我想为SortedDictionary编写自定义比较器,其中键根据其类型进行排序。这可能吗?

public class StateBase
{
    // This is a base class I have to inherit from
}

SortedDictionary<StateBase, int> _stateDictionary =
    new SortedDictionary<StateBase, int>(new StateComparer());

class StateComparer : IComparer<StateBase>
{
    public int Compare(StateBase a, StateBase b)
    {
        // I'd like to sort these based on their type
        // I don't particularly care what order they are in, I just want them
        // to be sorted.
    }
}

2 个答案:

答案 0 :(得分:1)

当然,为什么不呢?请注意,我们必须讨论要应用的引用类型,例如:

public class TypeComparer<T> : IComparer<T>, IEqualityComparer<T> where T : class
{
    public static readonly TypeComparer<T> Singleton= new TypeComparer<T>();
    private TypeComparer(){}
    bool IEqualityComparer<T>.Equals(T x, T y)
    {
        if (ReferenceEquals(x, y)) return true;
        if (x == null || y == null) return false;
        Type xType = x.GetType(), yType = y.GetType();
        return xType == yType && EqualityComparer<T>.Default.Equals(x, y);
    }
    int IEqualityComparer<T>.GetHashCode(T x)
    {
        if (x == null) return 0;
        return -17*x.GetType().GetHashCode() + x.GetHashCode();
    }
    int IComparer<T>.Compare(T x, T y)
    {
        if(x==null) return y == null ? 0 : -1;
        if (y == null) return 1;

        Type xType = x.GetType(), yType = y.GetType();
        int delta = xType == yType ? 0 : string.Compare(
               xType.FullName, yType.FullName);
        if (delta == 0) delta = Comparer<T>.Default.Compare(x, y);
        return delta;
    }
}

答案 1 :(得分:0)

你可以。如果您的比较器实现IComparer<T>,则可以通过相应的constructor overload将其传递给新的SortedDictionary实例。

Compare方法然后以某种方式决定哪个项目更大或更低。在这里您可以实现按类型比较的逻辑。

以下是根据名称比较Type个实例的示例:

public class TypeComparer : IComparer<Type>
{
    public int Compare(Type x, Type y)
    {
        if(x != null && y != null)
            return x.FullName.CompareTo(y.FullName);
        else if(x != null)
            return x.FullName.CompareTo(null);
        else if(y != null)
            return y.FullName.CompareTo(null);
        else
            return 0;
    }
}
相关问题