将具有整数索引的Dictionary转换为数组以使数组索引为Dictionary索引的最快方法是什么?您可以假定字典包含从0到最大键的所有元素。
示例:
dictionary[2] = z
dictionary[0] = x
dictionary[1] = y
转换后,我需要:
array[0] = x
array[1] = y
array[2] = z
答案 0 :(得分:2)
如果字典中的键/值包含数组中的索引,您想要将该值放置到数组中,就可以遍历字典并将该值插入到特定索引中。
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;
如果索引不按@TanvirArjel的建议递增,则-您应该首先找到最大索引,这意味着将第二行替换为以下内容:
string[] arr = new string[keyValuePairs.Keys.Max() + 1];
从速度角度来看,最好使用非延迟编程并定义类型。.迭代时,使用vars 可以获得的性能提升较小(以下支持参数)。
有一篇很棒的Microsoft文章here比较了字典的迭代方式及其速度。