views:

231

answers:

3

A SorteDictionary is according to MSDN sorted on the key. Does that mean that you can be sure that it will be sorted when you enumerate it in a foreach? Or does it just mean that the SortedDictionary works that way internally to have better performance in various cases?

A: 

Yes, that's exactly what it means.

Edit: the part that says "Does that mean that you can be sure that it will be sorted when you enumerate it in a foreach?"

280Z28
Which one of them? :p
Svish
Is it guaranteed that it is sorted? (as compared to the the regular Dictionary where it is not)
Svish
+2  A: 

When you enumerate the collection it is sorted by keys (even if you enumerate say the Values collection). Internally the collection is implemented as a binary search tree (according to the documentation). Both insertion and lookup of values are O(log n) (meaning they are pretty efficient).

Martin Liversage
+2  A: 

From MSDN:

The dictionary is maintained in a sorted order using an internal tree. Every new element is positioned at the correct sort position, and the tree is adjusted to maintain the sort order whenever an element is removed. While enumerating, the sort order is maintained.

Sam Saffron
Lol. Where does it say that? I read like... all of it... must be getting blind...
Svish