Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the order of Dictionary.Values.ToArray()?

Tags:

c#

dictionary

If I am adding values to a dictionary and then later in the code somewhere, I want to convert that dictionary to an Array using:

myDictionary.Values.ToArray()

Will the array come out in the order I entered it? Or is it sorted at some stage?

like image 575
Joel Avatar asked May 28 '11 10:05

Joel


2 Answers

If you want the values sorted (on the Key) then you should use a SortedDictionary<K,V> or a SortedList<K,V>

For a normal Dictionary the order of the Values is implementation-dependent but you may as well assume it's random.

The order of entering is lost.

like image 192
Henk Holterman Avatar answered Oct 13 '22 01:10

Henk Holterman


The order in which the values is returned is most likely(but not guaranteed) to be the same order in which the keys are stored. As mentioned by Henk Holterman, this is implementation specific and should not be relied upon.

MSDN entry for Dictionary is very explicit about this:

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

EDIT Dictionary may lure you into a false sense of security by seemingly returning values in the order they were added, but below passing test demonstrates that its behaviour is actually much more subtle:

[TestMethod]
public void TestDictionary()
{
    var dictionary1 = new Dictionary<int, int>();
    var dictionary2 = new Dictionary<int, int>();
    for(int i = 0; i < 10; i++){
        dictionary1[i] = i;
        if (i != 3)
            dictionary2[i] = i;
    }

    dictionary1.Remove(3);
    dictionary1[3] = 3;
    dictionary2[3] = 3;

    CollectionAssert.AreEqual(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, dictionary1.Values);
    CollectionAssert.AreEqual(new[] { 0, 1, 2, 4, 5, 6, 7, 8, 9, 3 }, dictionary2.Values);
}

If you look closely at the code, you will see that the order of the elements in the dictionary is not the order in which elements are added, but the order in which elements are originally added.

I don't event want to imagine what happens with multiple insertions and deletions over time. If you rely on this undocumented behaviour, I think you will owe the world an equivalent of US national debt in bad code offsets.

like image 35
Igor Zevaka Avatar answered Oct 13 '22 01:10

Igor Zevaka