Reputation: 105
What is the fastest way to convert a Dictionary with integer index to an array such that the array index is the Dictionary index? You can assume the Dictionary contains all elements from 0 to the maximum key.
Example:
dictionary[2] = z
dictionary[0] = x
dictionary[1] = y
After conversion I need:
array[0] = x
array[1] = y
array[2] = z
Upvotes: 1
Views: 2666
Reputation: 8597
If the key/value in the dictionary contains the index in the array you want to put the value to you can just iterate over the dictionary and insert the value to specific index.
Dictionary<int, string> keyValuePairs = new Dictionary<int, string>();
string[] arr = new string[keyValuePairs.Count];
foreach (KeyValuePair<int, string> item in keyValuePairs)
arr[item.Key] = item.Value;
Should you have indexes not incrementing uniformly as @TanvirArjel suggested - you should first find the maximum index which would mean replacing the second line to the following:
string[] arr = new string[keyValuePairs.Keys.Max() + 1];
Speed wise, it's always better to use non-lazy programming and define your types.. you'll get a smaller performance increase over using vars when iterating (Supporting argument below).
There's a great Microsoft Article here comparing the ways of iteration and their speed on Dictionaries.
Upvotes: 2