Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the Enumerator of a Dictionary<TKey, TValue> return key value pairs in the order they were added?

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:

  • Added 20 key value pairs to a Dictionary
  • Retrieved them by doing a foreach(KeyValuePair...)

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

Is this by design?

like image 974
SharePoint Newbie Avatar asked Sep 21 '09 07:09

SharePoint Newbie


People also ask

What is TKey and TValue?

Type ParametersTKey. The type of the keys in the dictionary. TValue. The type of the values in the dictionary. Inheritance.

Can we store duplicate values in Dictionary c#?

It is not possible. All keys should be unique.

What does a Dictionary do 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.


2 Answers

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

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.

like image 200
Jon Skeet Avatar answered Sep 26 '22 06:09

Jon Skeet


From MSDN:

For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair<(Of <(TKey, TValue>)>) structure representing a value and its key. The order in which the items are returned is undefined.

[Emphasis added]

like image 35
heijp06 Avatar answered Sep 22 '22 06:09

heijp06