1

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.
    }
}
4

2 に答える 2

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;
    }
}
于 2012-07-05T08:44:47.310 に答える
0

あなたはできる。比較子が を実装している場合、対応するコンストラクターのオーバーロードによって新しいインスタンスIComparer<T>に渡すことができます。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;
    }
}
于 2012-07-05T08:39:22.463 に答える