Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary item order

Tags:

c#

dictionary

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?

like image 673
joe Avatar asked Aug 19 '13 09:08

joe


1 Answers

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?

like image 140
Tim Schmelter Avatar answered Oct 05 '22 23:10

Tim Schmelter