views:

350

answers:

6

Hi,

I understand that a dictionary is not an ordered collection and one should not depend on the order of insertion and retrieval in a dictionary.

However, this is what I noticed:

  • Added 20 key value pairs to a Dictionary
  • Retrieved them by doing a foreach(KeyValuePair...)

The order of retrieval was same as the order in which they were added. Tested for around 16 key value pairs.

Is this by design?

+14  A: 

From MSDN:

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

[Emphasis added]

Peter van der Heijden
A: 

I don't think so, the dictionary does not grantee the internal ordering of items inside it. If you need to keep the order as well, use additional data structure (array or list) along with the dictionary.

Dror Helper
+9  A: 

It's by coincidence, although predictably so. You absolutely shouldn't rely on it. Usually it will happen for simple situations, but if you start deleting elements and replacing them with anything either with the same hash code or just getting in the same bucket, that element will take the position of the original, despite having been added later than others.

It's relatively fiddly to reproduce this, but I managed to do it a while ago for another question:

using System;
using System.Collections.Generic;

class Test
{
    static void Main(string[] args)
    {
        var dict = new Dictionary<int, int>();        
        dict.Add(0, 0);
        dict.Add(1, 1);
        dict.Add(2, 2);
        dict.Remove(0);
        dict.Add(10, 10);

        foreach (var entry in dict)
        {
            Console.WriteLine(entry.Key);
        }
    }
}

The results show 10, 1, 2 rather than 1, 2, 10.

Note that even though it looks like the current behaviour will always yield elements in insertion order if you don't perform any deletions, there's no guarantee that future implementations will do the same... so even in the restricted case where you know you won't delete anything, please don't reply on this.

Jon Skeet
+1 - this example helped me to reproduce the behaviour in my scenario so I could "see" it in action, helping me to avoid potential pitfalls.
AdaTheDev
A: 

I believe enumerating a Dictionary<K,V> will return the keys in the same order they were inserted if all the keys hash to the same value. This is because the Dictionary<K,V> implementation uses the hash code of the key object to insert key/value pairs into buckets, and the values are (usually) stored in the buckets in the order they are inserted. If you are consistently seeing this behavior with your user-defined objects, then perhaps you have not (correctly) overridden the GetHashCode() method?

Daniel Pryden
+1  A: 

It is by design that the Dictionary<TKey,TValue> is not an ordered structure as it is intended to be used primarily more for key-based access.

If you have the need to retrieve items in a specific order, you should take a look at the Sorted Dictionary<TKey, TValue>, which takes a Comparer<T> that will be used to sort the keys in the Sorted Dictionary<TKey, TValue>.

Russ Cam
I think you may have misread the question. He's asking whether the fact that he *is* seeing the results in order is by design.
Jon Skeet
thanks Jon, I meant the fact that the dictionary is not an ordered structure is by design. I'll better clarify my answer (it can be tricky answering on an iPhone on the train :) )
Russ Cam
@Russ: Yes - I realised what you were saying, but it's not answering the "is it by design" question which was asked :)
Jon Skeet
+2  A: 

If you want to iterate through a Dictionary in a fixed order you could try OrderedDictionary

Yannick M.