为什么在.Net字典中添加订单的条目? [英] Why are entries in addition order in a .Net Dictionary?

查看:107
本文介绍了为什么在.Net字典中添加订单的条目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚看到这个行为,我有点惊讶...

I just saw this behaviour and I'm a bit surprised by it...

如果我添加3或4个元素到一个字典,然后做一个For Each获得所有的密钥,它们按照我添加的相同顺序出现。

If I add 3 or 4 elements to a Dictionary, and then do a "For Each" to get all the keys, they appear in the same order I added them.

这令我惊奇的原因是字典应该是一个哈希表在内部,所以我预计事情会以任何顺序出现(按键的哈希排序,是吗?)

The reason this surprises me is that a Dictionary is supposed to be a HashTable internally, so I expected things to come out in ANY order (ordered by the hash of the key, right?)

我在这里缺少什么?
这是我可以指望的一个行为吗?

What am I missing here? Is this a behaviour I can count on?

编辑:好的,我以为已经有很多原因可能这个可能发生(像单独的列表到条目,这是否是巧合等)。
我的问题是,有没有人知道如何真正有效?

OK, I thought already of many of the reasons why this might happen (like the separate list to entries, whether this is a coincidence, etc). My question is, does anyone know how this really works?

推荐答案

如果你在3.5类库中使用.NET Reflector,您可以看到Dictionary实现将项目存储在数组中(根据需要调整大小),并将索引散列到该数组中。获取密钥时,它完全忽略了哈希表,并遍历了数组。因此,在数组末尾添加新项目后,您将看到所描述的行为。看来,如果您执行以下操作:

If you use .NET Reflector on the 3.5 class libraries you can see that the implementation of Dictionary actually stores the items in an array (which is resized as needed), and hashes indexes into that array. When getting the keys, it completely ignores the hashtable and iterates over the array of items. For this reason, you will see the behavior you have described since new items are added at the end of the array. It looks like if you do the following:

add 1
add 2
add 3
add 4
remove 2
add 5

您将获得1 5 3 4因为它重用空插槽。

you will get back 1 5 3 4 because it reuses empty slots.

重要的是要注意,像许多其他人一样,你将来(或过去)的版本不能指望这个行为。如果您希望排序您的字典,那么 SortedDictionary 类别这个目的。

It is important to note, like many others have, you cannot count on this behavior in future (or past) releases. If you want your dictionary to be sorted then there is a SortedDictionary class for this purpose.

这篇关于为什么在.Net字典中添加订单的条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆