字典的枚举器<TKey, TValue>按添加顺序返回键值对? [英] Does the Enumerator of a Dictionary<TKey, TValue> return key value pairs in the order they were added?

查看:36
本文介绍了字典的枚举器<TKey, TValue>按添加顺序返回键值对?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道字典不是有序集合,不应依赖于字典中插入和检索的顺序.

I understand that a dictionary is not an ordered collection and one should not depend on the order of insertion and retrieval in a dictionary.

然而,这是我注意到的:

However, this is what I noticed:

  • 向字典添加了 20 个键值对
  • 通过执行 foreach(KeyValuePair...) 检索它们

检索顺序与添加顺序相同.测试了大约 16 个键值对.

The order of retrieval was same as the order in which they were added. Tested for around 16 key value pairs.

这是故意的吗?

推荐答案

这纯属巧合,虽然在意料之中.你绝对不应该依赖它.通常它在简单的情况下发生,但是如果你开始删除元素并用任何具有相同哈希码或只是进入同一个存储桶的东西替换它们,该元素将占据原始位置,尽管添加得比其他人晚.

It's by coincidence, although predictably so. You absolutely shouldn't rely on it. Usually it will happen for simple situations, but if you start deleting elements and replacing them with anything either with the same hash code or just getting in the same bucket, that element will take the position of the original, despite having been added later than others.

重现这个相对繁琐,但我不久前设法做到了另一个问题:

It's relatively fiddly to reproduce this, but I managed to do it a while ago for another question:

using System;
using System.Collections.Generic;

class Test
{
    static void Main(string[] args)
    {
        var dict = new Dictionary<int, int>();        
        dict.Add(0, 0);
        dict.Add(1, 1);
        dict.Add(2, 2);
        dict.Remove(0);
        dict.Add(10, 10);

        foreach (var entry in dict)
        {
            Console.WriteLine(entry.Key);
        }
    }
}

结果显示为 10, 1, 2 而不是 1, 2, 10.

The results show 10, 1, 2 rather than 1, 2, 10.

请注意,即使看起来 当前 的行为在您不执行任何删除操作的情况下始终会按插入顺序生成元素,但不能保证未来的实现会做同样的事情......所以即使在您知道不会删除任何内容的受限情况下,也请不要依赖于此.

Note that even though it looks like the current behaviour will always yield elements in insertion order if you don't perform any deletions, there's no guarantee that future implementations will do the same... so even in the restricted case where you know you won't delete anything, please don't rely on this.

这篇关于字典的枚举器&lt;TKey, TValue&gt;按添加顺序返回键值对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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