views:

250

answers:

2

In Silverlight3, when a generic Dictionary is iterated with foreach and a KeyValuePair, is the iteration guaranteed to visit the items in the dictionary in the order in which the items were added? That is, the iteration sequence has nothing to do with the key's datatype or its value? The documentation is less than explicit on this:

This code will produce output similar to the following: http://msdn.microsoft.com/en-us/library/bwabdf9z.aspx (emphasis added)

Dictionary<String, Object> 
foreach (KeyValuePair String, Object kvp in myDictionary) {}

Dictionary<UInt16, String> 
foreach (KeyValuePair UInt16, String kvp in myDictionary) {} 

Thanks

+1  A: 

The iteration order depends on the key's hash codes and has nothing to do the the order in which they were added

SLaks
A: 

I would not make code dependent on a specific sort order. If you need a collection/dictionary that iterates with a specific order, you should order it first (using the Linq OrderBy method). Even if your code is fine today, you might want to take advantage of the upcoming parallel execution of tasks, and then have to revisit the implementation details of your code.

GreenIcicle
Thanks for the helpful replies.
Tim