Say, if I create a dictionary like this:
Dictionary<string, MyClass> dic = new Dictionary<string, MyClass>();
dic.add("z1", val1);
dic.add("abc9", val2);
dic.add("abc8", val3);
dic.add("ABC1", val4);
So when I do:
foreach (KeyValuePair<string, MyClass> kvp in dic)
{
}
Am I guaranteed to have these values retrieved as such: "z1", "abc9", "abc8", "ABC1"?
And what if I first do this, will it be: "z1", "abc8", "ABC1"?
dic.Remove("abc9");
Am I guaranteed to have these values retrieved as such: "z1", "abc9", "abc8", "ABC1"?
Absolutely not. Always treat Dictionary<,>
as an unordered collection of key/value pairs. Even though as an implementation detail you'll generally see them in insertion order if you only ever add values, you should not rely on this.
From the documentation:
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.
(Emphasis mine.)
If you need a particular order, you should use a different collection - potentially in conjunction with a dictionary, if you also need to be able to fetch by key. (It's not entirely uncommon to maintain an IList<TKey>
as well as a Dictionary<TKey, TValue>
for example.)
See more on this question at Stackoverflow