If the goal is to create a generic read-only dictionary that preserves insertion order, can SortedList<,> or SortedDictionary<,> be realiably used with an IComparer<> that attempts to maintain insertion order by doing something similar to the following?
class OrderedComparer<T> : IComparer<M>
{
public int Compare(M x, M y)
{
return x.Equals(y) ? 0 : -1;//or 1
}
}
SortedList<M> orderedList = new SortedList<M>(new OrderedComparer<T>());
(It's interesting that in the case of SortedDictionary, the above method need to return 0 or 1 in order to prevent the elements from being sorted in the reverse insertion order).
A comparer must obey the law
Compare(a, b) == -Compare(b, a) //assuming only possible values are -1, 0, 1
This is the symmetry property. Your sample code does not obey it. Therefore the BCL collections do not give you any guarantee at all. You have violated the documented contract.
You can't do this.
Instead, you could add a new field to M
where you store the insertion order as an int
. You can then use that field in the comparer.