简体   繁体   English

在C#中将Dictionary映射到数组的最快方法

[英]Fastest way to map Dictionary to array in C#

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. 您可以假定字典包含从0到最大键的所有元素。

Example: 例:

dictionary[2] = z
dictionary[0] = x
dictionary[1] = y

After conversion I need: 转换后,我需要:

array[0] = x
array[1] = y
array[2] = z

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: 如果您的索引不按照@TanvirArjel的建议一致地递增-您应该首先找到最大索引,这意味着将第二行替换为以下内容:

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). 在速度方面,最好使用非延迟编程并定义您的类型。.进行迭代时,与使用vars相比,您将获得较小的性能提升(下面的Supporting参数)。

There's a great Microsoft Article here comparing the ways of iteration and their speed on Dictionaries. 有一个伟大的Microsoft文章在这里比较迭代的方式和他们的字典速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM