Reputation: 6082
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:
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?
Upvotes: 21
Views: 6822
Reputation: 5895
Is this by design? It probably wasn't in the original .Net Framework 2.0, but now there is an implicit contract that they will be ordered in the same order as added, because to change this would break so much code that relies on the behaviour of the original generic dictionary. Compare with the Go language, where their map deliberately returns a random ordering to prevent users of maps from relying on any ordering [1].
Any improvements or changes the framework writers make to Dictionary<T,V>
would have to keep that implicit contract.
[1] "Since the release of Go 1.0, the runtime has randomized map iteration order. ", https://blog.golang.org/go-maps-in-action .
Upvotes: 3
Reputation: 125488
It is by design that the Dictionary<TKey,TValue>
is not an ordered structure as it is intended to be used primarily more for key-based access.
If you have the need to retrieve items in a specific order, you should take a look at the Sorted Dictionary<TKey, TValue>
, which takes a Comparer<T>
that will be used to sort the keys in the Sorted Dictionary<TKey, TValue>
.
Upvotes: 3
Reputation: 1500385
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.
Upvotes: 35
Reputation: 11788
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]
Upvotes: 22
Reputation: 35971
If you want to iterate through a Dictionary in a fixed order you could try OrderedDictionary
Upvotes: 4
Reputation: 60957
I believe enumerating a Dictionary<K,V>
will return the keys in the same order they were inserted if all the keys hash to the same value. This is because the Dictionary<K,V>
implementation uses the hash code of the key object to insert key/value pairs into buckets, and the values are (usually) stored in the buckets in the order they are inserted. If you are consistently seeing this behavior with your user-defined objects, then perhaps you have not (correctly) overridden the GetHashCode()
method?
Upvotes: 0
Reputation: 30790
I don't think so, the dictionary does not grantee the internal ordering of items inside it. If you need to keep the order as well, use additional data structure (array or list) along with the dictionary.
Upvotes: 0