谁在字典<>。第一()?谁在、字典、GT、LT

2023-09-02 01:50:10 作者:忘了怎么笑

什么是.NET 3.5扩展方法的含义 Enumerable.First()当你调用它的词典收藏?

What is the meaning of the .NET 3.5 extension method Enumerable.First() when you call it on an instance of the Dictionary collection?

是否设定键,确定哪个项目是第一个,还是只是没有定义?

Does the set of keys determine which item is first, or is it just not defined?

推荐答案

好了,我相信键组的将会的决定哪些项目是第一个,但不是在一个明确定义的(或易predict)的方式。换句话说,不要以为它会永远以同样的方式 - 这是不安全的依靠散列code实现保持相同的运行之间

Well, I believe the set of keys will determine which item is first, but not in a well-defined (or easy to predict) way. In other words, don't assume that it will always work the same way - it's as unsafe as relying on a hash code implementation staying the same between runs.

编辑:我认为,事实上,插入的顺序的确实的事情,出乎我的previous想法。然而,这种的是的具体实现的(因此可能在未来的版本很容易地改变)。我相信,在目前的执行情况,所添加的第一个第一个条目返回的如果的它并没有被删除。如果添加的第一个条目上移除,排序被打破 - 这不是说的最早的的条目被删除。这里有一个例子:

I believe that in fact, the ordering of insertion does matter, contrary to my previous ideas. However, this is implementation-specific (so could easily change in the next version). I believe that with the current implementation, the first entry added will be the first one returned if it hasn't been removed. If the first entry added is ever removed, the ordering is broken - it's not that the earliest entry is removed. Here's an example:

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);
        }
        Console.WriteLine("First key: " + dict.First().Key);
    }
}

的结果是10,1,2,和第一个键:10 - 显示出的最新的添加条目最终被退回第一

The results are 10, 1, 2, and "First key: 10" - showing that the latest added entry ends up being returned first.

不过,我想再次强调,一切都可以在Framework版本之间切换。

However, I'd like to stress again that everything can change between versions of the framework.