3

Is there an elegant way to get a dictionary's keys and values in the same order? I am worried that if I use dict.Values.ToArray() and dict.Keys.ToArray() (or dict.Select(obj => obj.Key) and dict.Select(obj => obj.Value)), that they won't be in the same order.

The simple way to execute this is:

foreach (var keyAndVal in dict)
{
    keyList.Add(keyAndVal.Key);
    valueList.Add(keyAndVal.Value);
}
var keyArray = keyList.ToArray();
var valueArray = valueList.ToArray();

To me, this feels like the kind of thing that LINQ was made for (but I know that dictionary iteration order is not guaranteed to stay the same in two different calls). Is there an elegant (i.e. LINQ, etc.) way to get these in the same order?

Thanks a lot for your help.

user
  • 6,723
  • 6
  • 41
  • 86
  • 4
    You can use `Values`, from [the docs](http://msdn.microsoft.com/en-us/library/ekcfxy3x.aspx): "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." – vcsjones Oct 23 '13 at 15:01
  • Good question. I have used `dict.Values.ToArray()` and it has given me different results in different environments. – Senura Dissanayake Jun 21 '19 at 08:46

1 Answers1

3

As vcsjones points out, for a standard dictionary, the Keys and Values collections will be in the same order. However, if you want a method that will create key and value arrays that will always be in the same order, for any implementation of IDictionary<TKey, TValue>, you could do something like this:

var keyArray = new TKey[dict.Count];
var valueArray = new TValue[dict.Count];
var i = 0;
foreach (var keyAndVal in dict)
{
    keyArray[i] = keyAndVal.Key;
    valueArray[i] = keyAndVal.Value;
    i++;
}
Community
  • 1
  • 1
p.s.w.g
  • 136,020
  • 27
  • 262
  • 299