为什么在.NET词典除了订单项?单项、词典、NET

2023-09-02 10:33:18 作者:无法企及的光、

我刚刚看到这种行为,我有点被它感到惊讶......

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

如果我加3或4元到词典,然后做了为每一个让所有的钥匙,他们出现在我加入他们的顺序相同。

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?

推荐答案

如果您使用.net反射在3.5类库可以看到字典的实现实际上存储项目中的数组(按照需要调整大小)和散列索引到该阵列。当得到的钥匙,它完全忽略了哈希表和迭代项目的数组。出于这个原因,你会看到你所描述的,因为新的项目添加到数组的结尾的行为。看起来,如果你做了以下这样的:

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.