Reputation: 11963
based on the doc
The order of the keys in the Dictionary.KeyCollection is unspecified
Ok I'm fine with that. But what if I did not modify the dictionary's key nor its values.
Lets say if I do
Dictionary.Keys.ToList();
Thread.Sleep(5000)
Dictionary.Keys.ToList();
can I safely assume the order would be the same?
Upvotes: 2
Views: 144
Reputation: 726539
Iterating a Dictionary
is a deterministic process. It is based on the implementation-specific way the items are organized inside hash "buckets", tie resolution, and insertion order.
However, the order of iterating a dictionary does not depend on anything arbitrary that could change between iterations. You can see how the iteration is done in the source of Dictionary.Enumerator
here: its bool MoveNext()
method walks dictionary.entries[index]
array one by one, stopping when the first unused element is reached. Hence you can safely assume that the order of iterating a dictionary is not going to change when you do not modify the dictionary between iterations.
Upvotes: 3