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?
Type ParametersTKey. The type of the keys in the dictionary. TValue. The type of the values in the dictionary. Inheritance.
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.
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.
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)
You're looking for SortedDictionary<K,V>
. Dictionary<K,V>
uses hashing, which with small sets may look superficially similar to sorting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With