Reputation: 190769
I have C# Dictionary.
Dictionary<string, string> map = new Dictionary<string, string>();
map["x"] = "1";
map["z"] = "2";
map["y"] = "0";
When I get the keys with foreach
, I get the value of "x"-"z"-"y". And this is the sequence that I give input to the map.
foreach (var pair in map)
{
Console.WriteLine(pair.Key);
}
Is this guaranteed behavior? I mean, with Dictionary, do I always get the elements in FIFO way with foreach?
Upvotes: 4
Views: 2169
Reputation: 10785
They are typically ordered by the key - x, y, z in your case.
Upvotes: -1
Reputation: 17909
Nope, A dictionary is not guaranteed to order its contents in the way they were inserted.
To quote the blurb from MSDN:
'For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair(Of TKey, TValue) structure representing a value and its key. The order in which the items are returned is undefined.'
Upvotes: 6