I have a requirement to retrieve an item from a data structure by key. But I also have a requirement to traverse that data structure in sorted order, using a field other than the key.
Something like this (pseudocode, for illustrative purposes only):
var list = new SortedDictionary<TKey, TSortField, TItem>();
How would I do this? Is there a way to use a single data structure, or do I need to roll my own?
NOTE: TItem already derives from (and implements)IComparable<T>.
If you’re not going to be modifying the result of the sort, you could use a combination of IEnumerable.OrderBy and ToDictionary:
Just keep in mind that this is really creating a new collection rather than sorting the original (which will be maintained in the SortedDictionary).