The short answer is that there should be no way, because the dictionary "Represents a collection of keys and values." which does not imply any orders. Any hack you can find is outside the class definition and can be changed.
You should probably first ask yourself if a dictionary is really needed in this situation, or if you can use the KeyValuePairs list.
Otherwise, the following may be useful:
public class IndexableDictionary<T1, T2> : Dictionary<T1, T2> { private SortedDictionary<int, T1> _sortedKeys; public IndexableDictionary() { _sortedKeys = new SortedDictionary<int, T1>(); } public new void Add(T1 key, T2 value) { _sortedKeys.Add(_sortedKeys.Count + 1, key); base.Add(key, value); } private IEnumerable<KeyValuePair<T1, T2>> Enumerable() { foreach (T1 key in _sortedKeys.Values) { yield return new KeyValuePair<T1, T2>(key, this[key]); } } public new IEnumerator<KeyValuePair<T1, T2>> GetEnumerator() { return Enumerable().GetEnumerator(); } public KeyValuePair<T1, T2> this[int index] { get { return new KeyValuePair<T1, T2> (_sortedKeys[index], base[_sortedKeys[index]]); } set { _sortedKeys[index] = value.Key; base[value.Key] = value.Value; } } }
With client code, it looks something like this:
static void Main(string[] args) { IndexableDictionary<string, string> fooDict = new IndexableDictionary<string, string>(); fooDict.Add("One", "One"); fooDict.Add("Two", "Two"); fooDict.Add("Three", "Three");
UPDATE: For some reason, he will not allow me to comment on my own answer.
In any case, IndexableDictionary differs from OrderedDictionary in that
- "OrderedDictionary elements are not sorted in any way." Therefore foreach would not pay attention to numeric indices
- It is strongly typed, so you don’t have to bother with customization from DictionaryEntry structures.