views:

2805

answers:

2

I'm using a Dictionary<TKey, TValue> and I'm getting some odd, though somewhat understandable behaviour in my tests.

No matter the order I add entries to the dictionary when I call Dictionary.Keys the keys are returned in the order specified by the IComparable<T> implementation for the key's type.

This is good for me as I want to get them in that order anyway, but I can't find anywhere that specifies that they should and will always be returned this way. Therefore, I don't know whether to rely on it always being like that or doing a (potentially redundant) sort on the List<T> I'm building.

Can I rely on this behaviour or not?

+14  A: 

You cannot rely on this behavior. This is just a coincidence that is likely due to your sample size or GetHashCode implementation. Once you add enough items into the table and force sufficient rehashes the keys will not be ordered.

MSDN explicitly says the order of the Keys is unspecified (http://msdn.microsoft.com/en-us/library/yt2fy5zk.aspx)

JaredPar
+11  A: 

You're looking for SortedDictionary<K,V>. Dictionary<K,V> uses hashing, which with small sets may look superficially similar to sorting.

Ruben Bartelink