I want to write a custom comparer for a SortedDictionary, where keys are sorted based on their type. Is this possible?
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.
}
}
You can. If your comparer implements
IComparer<T>, it can be passed to a newSortedDictionaryinstance by the corresponding constructor overload.The
Comparemethod then somehow decides what item is greater or lower. It is the place where you can implement your compare-by-type logic.Here is an example to compare
Typeinstances based on their name: