What is the order of Dictionary.Values.ToArray()?
If I am adding values to a dictionary and then later in the 开发者_C百科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?
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.
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.
If myDictionary
is of type Dictionary<K,V>
then the order is the same as the order used by Keys
and otherwise undefined. In particular it's not guaranteed to be the insertion order, or any kind of useful order or even that it's the same order on different runs of the same application.
The order of the values in the Dictionary.ValueCollection is unspecified, but it is the same order as the associated keys in the Dictionary.KeyCollection returned by the Keys property.
http://msdn.microsoft.com/en-us/library/ekcfxy3x.aspx
精彩评论