Garry Shutler
Garry Shutler

Reputation: 32698

Does Dictionary<TKey, TValue> order by the keys by default?

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?

Upvotes: 11

Views: 10733

Answers (2)

Ruben Bartelink
Ruben Bartelink

Reputation: 61795

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

Upvotes: 16

JaredPar
JaredPar

Reputation: 754665

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)

Upvotes: 24

Related Questions