Order-preserving data structures in C#
You should NOT expect either the keys or values in a regular Dictionary<TKey,TValue>
to be maintained in any order. In a SortedDictionary<TKey,TValue>
the keys and values are maintained in order by the value of the key - this is not the same as insertion order.
The only built-in dictionary in the .NET framework that preserves insertion order is System.Collections.Specialized.OrderedDictionary
. Unfortunately, this class is not generic - however, it's not terribly hard to write a generic wrapper around it. Keep in mind, when dealing with value types (like int
or double
) it will result in boxing of the keys/values (generic dictionaries don't impose boxing on value types).