为什么一个字典"没有下令"? [英] Why is a Dictionary "not ordered"?

查看:143
本文介绍了为什么一个字典"没有下令"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在回答阅读到许多问题就在这里。但是,究竟是什么意思呢?

I have read this in answer to many questions on here. But what exactly does it mean?

var test = new Dictionary<int, string>();
test.Add(0, "zero");
test.Add(1, "one");
test.Add(2, "two");
test.Add(3, "three");

Assert(test.ElementAt(2).Value == "two");

以上code似乎正常工作。因此,以什么方式是一个字典视为无序?在什么情况下可以在上述code失败?

The above code seems to work as expected. So in what manner is a dictionary considered unordered? Under what circumstances could the above code fail?

推荐答案

嗯,有一件事是你是否期望这是不清楚的插入顺序键序。例如,你会希望得到的结果是,如果你写的:

Well, for one thing it's not clear whether you expect this to be insertion-order or key-order. For example, what would you expect the result to be if you wrote:

var test = new Dictionary<int, string>();
test.Add(3, "three");
test.Add(2, "two");
test.Add(1, "one");
test.Add(0, "zero");

Console.WriteLine(test.ElementAt(0).Value);

你会想到三化或零?

Would you expect "three" or "zero"?

碰巧的是,我的认为的当前实现preserves插入排序,只要你不删除任何东西 - 但你的不能依赖这个的。这是一个实现细节,这可能在未来改变。

As it happens, I think the current implementation preserves insertion ordering so long as you never delete anything - but you must not rely on this. It's an implementation detail, and that could change in the future.

缺失也会影响到这一点。例如,你会想到这个程序的结果是什么?

Deletions also affect this. For example, what would you expect the result of this program to be?

using System;
using System.Collections.Generic;

class Test
{ 
    static void Main() 
    {
        var test = new Dictionary<int, string>();
        test.Add(3, "three");
        test.Add(2, "two");
        test.Add(1, "one");
        test.Add(0, "zero");

        test.Remove(2);
        test.Add(5, "five");

        foreach (var pair in test)
        {
            Console.WriteLine(pair.Key);
        }
    }     
}

这实际上是(在我的箱子)3,5,1,0 5的新条目已经用空出的条目previously使用2.这不会来保证任何虽然。

It's actually (on my box) 3, 5, 1, 0. The new entry for 5 has used the vacated entry previously used by 2. That's not going to be guaranteed either though.

老调重弹(字典的底层存储需要扩展时),可能会影响到的东西......各种各样的东西做的。

Rehashing (when the dictionary's underlying storage needs to be expanded) could affect things... all kinds of things do.

只是不要把它当作一个有序集合。它不是专为。即使发生了现在的工作,你依靠这违背类的目的,无证行为。

这篇关于为什么一个字典&QUOT;没有下令&QUOT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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