As we all know, Dictionary in C# theoretically does not preserve the order of the inserted elements.
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.
However, when I insert random keys into the dictionary and read them back in a foreach loop, they always come back in the insertion order.
Random rand = new Random();
var map = new Dictionary<int, int>();
for (int i = 0; i < 10; ++i)
{
var key = rand.Next(1000000000);
var value = 0;
Console.WriteLine($"Key: {key}");
if (map.ContainsKey(key))
continue;
map.Add(key,value);
}
Console.WriteLine("Reading Back..");
foreach (var pair in map)
{
Console.WriteLine($"Key: {pair.Key}");
}
The output from this code is like this:
Key: 593548784 Key: 765023454 Key: 1460074 Key: 913286745 Key: 804757753 Key: 281489700 Key: 395818098 Key: 227086287 Key: 323530161 Key: 629618868
Reading Back..
Key: 593548784 Key: 765023454 Key: 1460074 Key: 913286745 Key: 804757753 Key: 281489700 Key: 395818098 Key: 227086287 Key: 323530161 Key: 629618868
I'm surprised because I thought when elements are inserted to dictionary, hash key is determined by taking mod N of the key field, which would mean the order would be lost (unless N is extremely large).
Does anyone know why the behavior is like this?