开发者

Unexpected issue Copying Dictionaries

开发者 https://www.devze.com 2022-12-21 23:58 出处:网络
My idea was to copy a dictionary while resetting all the values of the previous one, so i have this instruction:

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

var dic开发者_如何学Python2 = 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?


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 :(


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)


.Net dictionaries are unordered.

Your question has no answer.

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号