-1

When iterating over a dictionary in C#, are we guaranteed that the order will be same every time we iterate this dictionary?

  foreach (var key in myDict.Keys)
  {
    ...               
  }
eflles
  • 6,606
  • 11
  • 41
  • 55
  • 1
    http://stackoverflow.com/questions/6384710/why-is-a-dictionary-not-ordered and http://stackoverflow.com/questions/4007782/the-order-of-elements-in-dictionary – Tim Schmelter Sep 02 '14 at 09:01
  • 1
    By the way, if you need an ordered dictionary use an [`OrderedDictionary`](http://msdn.microsoft.com/en-us/library/system.collections.specialized.ordereddictionary(v=vs.110).aspx). It has the same lookup performance but is slower on inserting/deleting and needs extra memory. – Tim Schmelter Sep 02 '14 at 09:20

1 Answers1

1

According to documentation, no, there is no guarantee:

The order of the keys in the Dictionary<TKey, TValue>.KeyCollection is unspecified,but it is the same order as the associated values in the Dictionary<TKey, TValue>.ValueCollection returned by the Values property.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184