views:

63

answers:

4

My idea was to copy a dictionary while resetting all the values of the previous one, so i have this instruction:

var dic2 = new Dictionary<string, int>(dic.ToDictionary(kvp => kvp.Key, kvp => 0));

However i had an unexpected problem doing this, since the new copied dictionary doesnt have the same order of keys of the previous one.

Any way to reset the values but to maintain the same order of keys? Witouth resorting to some type of sorting?

+7  A: 

The answer is not to rely on the order of keys in a Dictionary<,> in the first place. It's emphatically not guaranteed.

This is documented on MSDN, but not nearly as clearly as I'd have wanted:

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

.NET doesn't currently have an insertion-order-preserving dictionary implementation as far as I'm aware :(

Jon Skeet
Actually, it does - `KeyedCollection<TKey, TValue>`
SLaks
@SLaks: That's not a dictionary in terms of implementing `IDictionary<,>` - it doesn't let you put an arbitrary key/value pair in there. Yes, you could create a key/value pair and use the obvious key extraction - but at that stage you've gone through enough hoops that I don't think it can be deemed part of the framework...
Jon Skeet
+1  A: 

Dictionary doesn't define sequence of keys. It is not array or list. You should not rely on order of keys on dictionary. Dictionary was made for by-key access not for sequential.

Andrey
+3  A: 

.Net dictionaries are unordered.

Your question has no answer.

You should consider using a List<KeyValuePair<string, int>> instead.

SLaks
+3  A: 

The order of the keys in a Dictionary<K,V> isn't maintained. You might want to use a SortedDictionary<K,V> instead (note that this class sorts the entries based on the key, but doesn't allow an arbitrary order, unless you create a specific key comparer)

Thomas Levesque