0

I'd like to initialize a Dictionary with arrays of keys and values, as follows:

int[] keys = {1, 2, 3};
string[] values = {"a", "b", "c"};
Dictionary<int, string> dict = new Dictionary<int, string>(keys, values);

Is there a fast way to do it without iterating the arrays, as in:

for (int i = 0; i < keys.Length; ++i)
{
    dict.Add(keys[i], values[i]);
}

EDIT: someone marked this question as a duplicate of this one, but they are unrelated, as that question doesn't ask about turning keys-values collections to a dictionary, but a list of objects, each object holding a key and a list of values, to a dictionary.

OfirD
  • 9,442
  • 5
  • 47
  • 90

1 Answers1

5

Use Zip():

int[] keys = { 1, 2, 3 };
string[] values = { "a", "b", "c" };

var dict = keys.Zip(values, (num, str) => new { num = num, str = str })
            .ToDictionary(ns => ns.num, ns => ns.str);

It won't be faster, and for all I know it might actually be a little slower, though probably not by enough to matter.

The one clear advantage it has over your for loop is that Zip() won't throw an exception if values.Length < keys.Length.


Once the C#7 value tuple feature is usable without any nonsense, you'll be able to save a few characters:

var dict = keys.Zip(values, (num, str) => (num: num, str: str))
           .ToDictionary(ns => ns.num, ns => ns.str);