Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Who's on Dictionary<>.First()? [duplicate]

Tags:

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?

like image 382
Larry Fix Avatar asked Jan 12 '09 20:01

Larry Fix


People also ask

What is the dictionary in c#?

In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System. Collection.

How do you get the first element of the dictionary in unity?

Just use the Linq First() : var first = like. First(); string key = first. Key; Dictionary<string,string> val = first.

Does dictionary guarantee order?

Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.

Can a dictionary have multiple types?

One can only put one type of object into a dictionary. If one wants to put a variety of types of data into the same dictionary, e.g. for configuration information or other common data stores, the superclass of all possible held data types must be used to define the dictionary.


1 Answers

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.

EDIT: 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);
    }
}

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

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

like image 94
Jon Skeet Avatar answered Oct 24 '22 11:10

Jon Skeet