There are several questions on this site stating that Dictionaries don't have a guaranteed iteration order (which is typical of hash tables). However, I'm having trouble proving this out for the Dictionary class:
var dict = new Dictionary<string, int>();
var rand = new Random();
var randomList = Enumerable.Range(1, 1000)
.Select(i => new { x = rand.NextDouble().ToString(), i })
.ToArray();
foreach (var t in randomList) { dict[t.x] = t.i; }
Console.WriteLine(dict.Values.SequenceEqual(randomList.Select(t => t.i))); // prints True
Is this some undocumented behavior of the Dictionary class? Or am I simply missing something with my example?
EDIT: weirdly, this behavior is maintained for awhile but eventually stops as the dictionary gets larger. The cutoff seems to be 33899 (still prints true, whereas with 33900 it prints false). I suppose this could be related to a hash collision in this particular example.
The iteration order of Dictionary is not guaranteed. In practice, that means at the moment in does iterate in a consistent fashion, but in the future that may change.
If you write code that relies on Dictionary iterating in a deterministic way, then it's your problem if that breaks with a future .NET release as MS have advised not to rely on it.
Per MSDN (emphasis mine):
For purposes of enumeration, each item in the dictionary is treated as a
KeyValuePair<TKey, TValue>
structure representing a value and its key. The order in which the items are returned is undefined.
So while it may look like it's consistent, there's no guarantee that it'll remain that way in the future or across implementations.
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