3

I'm using a Dictionary<string, object> and I'm having an issue where I need to keep the items in the order they were placed in the dictionary, not in the alphabetical order of corresponding keys.

Is there a way to disable sorting of added items, or is it better to use some other custom class (I'd like to keep all dic[key] = value and other accessors as is)?

And if it's not possible with a Dictionary, what else can I use that still returns items by key?

user1306322
  • 8,561
  • 18
  • 61
  • 122

4 Answers4

7

The order that objects are stored in a Dictionary<> object isn't guaranteed to be any particular order. It's just optimized for access by key. If you need to guarantee the order of the objects, then you should use something else other than a Dictionary<>

Apparently there is a SortedDictionary<> class. I didn't even think to look for that, since it seems a bit antithetical to a Dictionary...

Tim
  • 14,999
  • 1
  • 45
  • 68
6

I need to keep the items in the order they were placed in the dictionary,

That does not comply with the main responsibilities of a Dictionary.

You can use a List<KeyValuePair<K,V>> or something else to match your requirements. Wrap it in a class with an indexer to get the dic[key] = value syntax.

H H
  • 263,252
  • 30
  • 330
  • 514
5

There is no such thing like order in Dictionary<TKey, TValue>:

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.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
1

You can use this:

List<KeyValuePair<T1,T2>>

The list does keep order of inserstion as oppsoed to Dictionary where order is defined internally.

Edit:

Since you want both ordering and [] getter, If you don't have issues with memory, you can build a wrapper class which holds the value in two internal collections:

A list and a dictionary. You will give in the wrapper getter by index (from the list) and getter by key (from the dictionary). Both list and dictionary need to be private, be sure to alwyas add and remove objects from both collections.

omer schleifer
  • 3,897
  • 5
  • 31
  • 42