Suppose I have a dictionary, and call .Keys, and then .Values with no intervening operations. Will the ordering of the keys be consistent with the ordering of the values?
Put another way, will the nth key correspond to the nth value as they did before in the dictionary?
Will the ordering of the keys be consistent with the ordering of the values?
Yes, it's guaranteed by the documentation of both IDictionary<,>.Keys
and IDictionary<,>.Values
.
Keys
documentation:
The order of the keys in the
Dictionary<TKey, TValue>.KeyCollection
is unspecified, but it is the same order as the associated values in theDictionary<TKey, TValue>.ValueCollection
returned by theValues
property.
Values
documentation:
The order of the values in the
Dictionary<TKey, TValue>.ValueCollection
is unspecified, but it is the same order as the associated keys in theDictionary<TKey, TValue>.KeyCollection
returned by theKeys
property.
See more on this question at Stackoverflow