First, on your primary assumption, you are correct. A normal dictionary makes no guarantees about the order of enumeration.
Second, you'll need to be careful about going the SortedDictionary
with custom IComparer
route. The comparer is used for key equality as well as sorting the collection. That is, using an IComparer
based on the addition order, you may have difficulty retrieving an element from a SortedDictionary
by key value, it might end up lost in the tree (which is the backing of a sorted dictionary).
If you're willing to go the C5 Generic Class Library route, you can get some good mileage out of a HashedLinkedList<KeyValuePair<T>>
or HashedLinkedList<T>
if T is self-keyed. You can create an IEqualityComparer
that will operate on the key to generate the hash code. Then retrieving the actual value, you can use Find(ref T x)
with a prototype x (perhaps where only the key is set) which will find the stored T
and return that by reference in O(1) time vs. O(log n) with a SortedDictionary
. As well, being backed by a LinkedList
, it is guaranteed to enumerate in addition order (and you can specify which direction you'd prefer through C5's IDirectedEnumerable
).
Hope that helps.