By same order, I don't mean the same order the keys were added!
Say,
1) I've a dictionary d
2) I add 2, 4, 6 as my keys like
- d.Add(2, "")
- d.Add(4, "")
- d.Add(6, "")
3) Now I access it via d.Keys property
- Say, it returns keys in order 4, 2, 6
Now by same order I mean, If I keep repeating steps 2 & 3.
Will d.Keys always return the keys in same order 4, 2, 6.
Given the fact that the same set of keys(2,4,6) are added every time and in the same order!
Basically is adding keys in dictionary a deterministic process ?
I've run a few sample random cases, and it appears that Dictionary.Keys property returns the same sequence every time for the same set of keys.
But is it guaranteed ?
Sample code I tried
public static void Main(string[] args)
{
var rand = new Random();
var fixedKeys = Enumerable.Range(1, 100000).Select(x => rand.Next(10000000)).Distinct().ToList();
var dic = new Dictionary<int, string>();
foreach (var item in fixedKeys)
{
dic.Add(item, "");
}
var fixedSequence = dic.Keys;
for (int j = 0; j < 10; j++)
{
dic = new Dictionary<int, string>();
foreach (var item in fixedKeys)
{
dic.Add(item, "");
}
if (!dic.Keys.SequenceEqual(fixedSequence))
{
Console.WriteLine("Order changed");
}
}
}