2

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?

Charles Taylor
  • 686
  • 6
  • 23
  • dictionaries are not guaranteed to have order. – Daniel A. White Aug 10 '15 at 17:23
  • probably its not clear, what you are asking – sujith karivelil Aug 10 '15 at 17:23
  • 1
    http://stackoverflow.com/questions/1453190/does-the-enumerator-of-a-dictionarytkey-tvalue-return-key-value-pairs-in-the – Daniel A. White Aug 10 '15 at 17:24
  • 5
    @DanielA.White: The order of the entries wasn't what the OP asked about - he was asking about whether the keys and values would be in the same order, and the answer is "yes". So while you can't predict what the order of keys will be (given just the contents) you *can* predict that it'll be consistent with the order of the values. – Jon Skeet Aug 10 '15 at 17:25
  • No. Especially if you have one key for many values like Dictionary>. The key for a dictionary is a hash table to reduce the time to extract items. – jdweng Aug 10 '15 at 19:43

2 Answers2

9

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 the Dictionary<TKey, TValue>.ValueCollection returned by the Values 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 the Dictionary<TKey, TValue>.KeyCollection returned by the Keys property.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    @OP: For readability reasons, I recommend against simultaneously enumerating the keys and values. `Dictionary` implements `IEnumerable>`, so a cleaner alternative is `foreach (KeyValuePair kvp in dict) {/*code*/}` – Brian Aug 11 '15 at 21:25
5

According to MSDN's documentation for Dictionary.Keys, yes.

The order of the keys in the Dictionary<TKey, TValue>.KeyCollection is unspecified, but it is the same order as the associated values in the Dictionary<TKey, TValue>.ValueCollection returned by the Values property.

glen3b
  • 693
  • 1
  • 8
  • 22