How to insert as first element in dictionary?

前端 未结 5 1533
伪装坚强ぢ
伪装坚强ぢ 2021-01-11 18:59

I have a dictionary structure, with multiple key value pairs inside.

myDict.Add(key1, value1);
myDict.Add(key2, value2);
myDict.Add(key3, value3);
         


        
5条回答
  •  星月不相逢
    2021-01-11 19:54

    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.

提交回复
热议问题