Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 771
Garry Shutler Avatar asked Feb 25 '09 13:02

Garry Shutler


People also ask

What is TKey and TValue?

Type ParametersTKey. The type of the keys in the dictionary. TValue. The type of the values in the dictionary. Inheritance.

How does Dictionary works internally in c#?

The Dictionary class in C# represents a generic data structure that can contain keys and values of data. Hence, you can store data of any type in a Dictionary instance.

What is Dictionary class in c#?

The Dictionary<TKey, TValue> Class in C# is a collection of Keys and Values. It is a generic collection class in the System. Collections. Generic namespace. The Dictionary <TKey, TValue> generic class provides a mapping from a set of keys to a set of values.


2 Answers

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)

like image 79
JaredPar Avatar answered Oct 13 '22 23:10

JaredPar


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

like image 30
Ruben Bartelink Avatar answered Oct 14 '22 00:10

Ruben Bartelink