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

If I add values ​​to the dictionary, and then to the code somewhere, I want to convert this dictionary to an array using:

myDictionary.Values.ToArray() 

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

+8
dictionary c #
source share
3 answers

If you want to sort the values ​​(on the key), you must use SortedDictionary<K,V> or SortedList<K,V>

For a normal Dictionary, the order of values ​​depends on the implementation, but you can consider it random.

The input order is lost.

+11
source share

The order in which the values ​​are returned is likely (but not guaranteed) to be the same order in which the keys are stored. As Henk Holterman mentioned, this is a concrete implementation, and you cannot rely on it.

The MSDN entry for the dictionary details this very closely:

For enumeration purposes, each element in the dictionary is treated as a KeyValuePair structure representing the value and its key. return order of items is undefined.

The EDIT Dictionary may lure you into a false sense of security, it would seem to return values ​​in the order in which they were added, but below the passing test it demonstrates that its behavior 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 of adding elements, but the order in which the elements were originally added.

I do not want to imagine what happens with multiple insertions and deletions over time. If you rely on this undocumented behavior, I think that you will owe the world the equivalent of US government debt in bad code offsets .

+9
source share

If myDictionary is of type Dictionary<K,V> , then the order is the same as the order used by Keys , otherwise undefined. In particular, this does not guarantee the insertion order or any useful order or even the same order on different runs of the same application.

The order of values ​​in Dictionary.ValueCollection is not specified, but it is the same order as the corresponding keys in Dictionary.KeyCollection returned by the Keys property.

http://msdn.microsoft.com/en-us/library/ekcfxy3x.aspx

+1
source share

All Articles