2

I have an array of keys and values from which I want to create a dictionary:

var keys = new string[] { "Key1", "Key2" };
var values = new string[] { "Bob", "Tim" };

The imperative way would be this:

var dictionary = new Dictionary<string, string>();
for(int i = 0; i < keys.Length; i++) {
  dictionary.Add(keys[i], values[i]);
}

How would I do this without loops? Probably with Linq? I've looked at Array.Join, but can't figure out how to make it work for me in this case.

3 Answers 3

6

You need Enumerable.Zip (to combine keys and values into single sequence) and Enumerable.ToDictionary (to convert that sequence to dictionary).

Sample:

var result = keys.Zip(values, (k,v) => new {k,v})
  .ToDictionary(p => p.k, p => p.v);
Sign up to request clarification or add additional context in comments.

Comments

6

There's an awesome ToDictionary extension method. The Range method is simply to loop over the indices, and it assumes that both arrays are not null and of the same length.

var dictionary = Enumerable.Range(0, keys.Length)
                     .ToDictionary(i => keys[i], i => values[i])

Comments

0

It's 2 loops anyway:

var dic = keys.Select((k, i) => new { Key = key, Value = values[i] })
              .ToDictionary(p => p.Key, p => p.Value);

assuming that keys and values are symmetric.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.