Steve
Steve

Reputation: 11963

is Dictionary.Keys order guarantee to be the same if the Dictionary has not been modified?

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

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

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

Related Questions