Is System.Collections.Generic.dictionary order preserved?

M

Magnus.Moraberg

Hi,

As I add items to a Dictionary, is the order that I add them
preserved?

I'm adding items from a sorted array to the dictionary using the Add
method, so I therefore add the items to the dictionary in a sorted
fashion. The question is, if I then use a foreach loop on my
dictionary, will this dictionary always print out in sorted order?

Thanks,

Barry
 
M

Magnus.Moraberg

"For purposes of enumeration, each item in the dictionary is treated as a
KeyValuePair(TKey, TValue) structure representing a value and its key. The
order in which the items are returned is undefined."

From:http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

There's all sorts of good, interesting stuff in the documentation. :)

Pete

Therefore I should copy the values from the Dictionary into an Array.
Then use Array.Sort() before printing, having added the interface
IComparable and implemented CompareTo() for the class of my values.
Correct?
 
M

Marc Gravell

Well, that would order them per the type's IComparable rules, not via
the original insertion order (by the way, I'd tend to implement
IComparable<T> in addition to IComparable). In this case (since the
original list was sorted), that might amount to the same thing...

If you want the data sorted by-key, then SortedList<TKey,TValue> or
SortedDictionary<TKey,TValue> might be suitable. If you want the data in
insertion order, then List<T> might be best.

Marc
 
A

Anthony Jones

Therefore I should copy the values from the Dictionary into an Array.
Then use Array.Sort() before printing, having added the interface
IComparable and implemented CompareTo() for the class of my values.
Correct?

You might find that SortedDictionary<TKey, TValue> suits your needs
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top