I have a dictionary structure, with multiple key value pairs inside.
myDict.Add(key1, value1);
myDict.Add(key2, value2);
myDict.Add(key3, value3);
Dictionary<K,V> does not have an ordering. Any perceived order maintenance is by chance (and an artifact of a particular implementation including, but not limited to, bucket selection order and count).
These are the approaches (just using the Base Class Libraries BCL) I know about:
O(n)
for "get(key)/set(key)")List<KeyValuePair<K,V>>
Happy coding.
Creating a hash data-structure that maintains insertion order is actually only a slight modification of a standard hash implementation (Ruby hashes now maintain insertion order); however, this was not done in .NET nor, more importantly, is it part of the Dictionary/IDictionary contract.
From the MSDN page on Dictionary(TKey, TValue):
For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair<(Of <(TKey, TValue>)>) structure representing a value and its key. The order in which the items are returned is undefined.
I'm assuming you can't use SortedDictionary because the control depends on your data source being a Dictionary. If the control expects both the Dictionary type and sorted data, the control needs to be modified, because those two criteria contradict each other. You must use a different datatype if you need sorting/ordering functionality. Depending on undefined behavior is asking for trouble.
Dictionary Should not be used to sort objects, it should rather be used to look up objects. i would suggest something else if you want to have it sort the objects too.
If you expand the Dictionary, there are no rule that would stop it from mixing up your List.
You cannot do that with the Dictionary
class. It is working in your example because of a quirk in the way the data structure is implemented. The data structure actually stores the entries in temporal order in one array and then uses another array to index into the entry array. Enumerations are based on the entry array. That is why it appears to be ordered in your case. But, if you apply a series of removal and insertion operations you will notice this ordering gets perturbed.
Use KeyCollection instead. It provides O(1) retrieval by both key and index and preserves temporal ordering.
Don't use a dictionary - there is no guarantee the order of the keys won't change when you add further elements. Instead, define a class Pair
for your Key-Value-Pairs (look here What is C# analog of C++ std::pair? for an example) and use a List<Pair>
for your datasource. The List
has an Insert
operation you can use to insert new elements anywhere into your list.