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.