Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C# Dictionary<TKey, TValue> guarantee an iteration order?

Tags:

c#

dictionary

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.

like image 517
ChaseMedallion Avatar asked Mar 21 '23 20:03

ChaseMedallion


2 Answers

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.

like image 83
David Arno Avatar answered Apr 25 '23 09:04

David Arno


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.

like image 26
Ahmad Mageed Avatar answered Apr 25 '23 10:04

Ahmad Mageed