Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I get the elements in Dictionary in a FIFO way with foreach in C#?

Tags:

c#

dictionary

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?

like image 638
prosseek Avatar asked Oct 17 '25 02:10

prosseek


1 Answers

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.'

like image 76
Russ Clarke Avatar answered Oct 18 '25 16:10

Russ Clarke