2

I'm currently adding items to a dictionary as below..

private Dictionary<string, Dictionary<string, object>> mydict = new Dictionary<string, Dictionary<string, object>>();

mydict.Add("string1", classobject1);

At the very end I wish to add "stringN" and classobjectN but I wish to add it as the first item in the dictionary.

Is the above possible?

johnnyRose
  • 7,310
  • 17
  • 40
  • 61
Arnab
  • 2,324
  • 6
  • 36
  • 60

2 Answers2

4

A dictionary does not preserve the order of insertion. From the doc: https://msdn.microsoft.com/en-us/library/xfhwa508(v=vs.110).aspx

For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair structure representing a value and its key. The order in which the items are returned is undefined.

E. Mourits
  • 295
  • 2
  • 11
3

Is the above possible?

No this is not possible.

Items stored in a dictionary are not stored in the order they added to the dictionary like in a list. The reason why this happens can be explained if you take a look at the data structures that are used to implement a list and a dictionary. In the case of a list an array is used. Whenever the array is get filled, another array of the double size is created and the elements of the first array are copied to the new array. Then the item you want to add is added to the new array. On the other hand, in the case of dictionary, a hash table is used. You could have a look here, in order to refresh the way a new item is added in a hash table.

Christos
  • 53,228
  • 8
  • 76
  • 108