Dictionary item order

c#, dictionary

Solution

They are not ordered at all. The order of elements in a dictionary is non-deterministic.

MSDN: "The order in which the items are returned is undefined."

You could use an `OrderedDictionary` instead to access an item via index. Or, if you want it to be ordered by the key you can use a `SortedDictionary`.

Update Why is a dictionary not ordered by nature?

Problem

I use a `Dictionary<string, Item>` to store own items. The reason for using a dictionary is that the keys are unique and accessing is fast. In most cases, I use the dicionary only to access single items. But in one case I have to loop through the dictionary - here I need to have the items in order they was added. I only know that the dictionary uses a hashtable internally, but I don't know how it is organized. Question: Are the items in a dictionary ordered as they are added? What happens to the order when items are added or removed?

Original source

Related problems