0

Consider registering entrance of new members in a Dictionary and the time of entrance:

Dictionary<string, DateTime> members = new Dictionary<string, DateTime>();
members.Add("Bob", DateTimeNow);
Thread.Sleep(1000);
members.Add("Joe", DateTimeNow);
Thread.Sleep(1000);
members.Add("Susan", DateTimeNow);
Thread.Sleep(1000);
// Now Joe exits
members.Remove("Joe");
// Then Mike enters
members.Add("Mike", DateTimeNow);

Now the question is where's Mike location in Dictionary. Is he added to the end of Dictionary or he will fill the empty location of Susan (if we iterate with foreach or access the Dictionary via index)? Is the behavior guaranteed for all of the times?

Xaqron
  • 29,931
  • 42
  • 140
  • 205
  • 2
    Why do you need to know this? Even if it may be that way, that is an implementation detail that you should not rely on! – Daniel Rose May 21 '11 at 19:20
  • 2
    "Is the behavior guaranteed for all of the times?" - No. – forsvarir May 21 '11 at 19:22
  • If the orders are guaranteed, then I can assume the first item is the earliest entrance and the last item is the latest entrance, so I don't need iterate and sort items. – Xaqron May 21 '11 at 19:26
  • To save storage, slots will be reused at least some of the time, so you can't rely on this. – Daniel Rose May 21 '11 at 19:31

3 Answers3

3

A Dictionary is not ordered, so you can't do any reasoning as to the order they're returned in if you iterate over the keys.

As the MSDN site tells us, Dictionary is implemented as a hash table, and:

The order in which the items are returned is undefined.

You should use a SortedDictionary if you want to iterate over the keys in a defined order.

nos
  • 223,662
  • 58
  • 417
  • 506
1

The notion of order is not defined for hashtable which what Dictionary represents. You can never rely on items being in a particular order. This behavior is not guaranteed. A Dictionary is used to quickly access a given item by key.

Quote from the documentation:

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

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

Accessing a Dictionary is done via key and not via index - so the question it self is meaning less.
As all answers already stated - a Dictionary has no order, and is implemented via a Hashtable (Wiki Page - Take the time to read it)

The Dictionary it self can expand and compress depending on the volume of data it maintains and its own implementation, but when using a rich framework like .NET your don't need to bother with that question, it is done for you. You can read the Dynamic Resizing section in the WIKI page to learn on the implementation if it interests you.

Daniel Rose
  • 17,233
  • 9
  • 65
  • 88
RonK
  • 9,472
  • 8
  • 51
  • 87