You can't sort a Dictionary<TKey, TValue>
- it's inherently unordered. (Or rather, the order in which entries are retrieved is implementation-specific. You shouldn't rely on it working the same way between versions, as ordering isn't part of its designed functionality.)
You can use SortedList<TKey, TValue>
or SortedDictionary<TKey, TValue>
, both of which sort by the key (in a configurable way, if you pass an IEqualityComparer<T>
into the constructor) - might those be of use to you?
Pay little attention to the word "list" in the name SortedList
- it's still a dictionary in that it maps keys to values. It's implemented using a list internally, effectively - so instead of looking up by hash code, it does a binary search. SortedDictionary
is similarly based on binary searches, but via a tree instead of a list.