toddmo toddmo -4 years ago 79
C# Question

Most elegant way to convert an array of even keys and odd values to a dictionary?

I have an array that has alternating keys and values because I don't know how to pass a dictionary in a GET in a url for the default binder.

the string array comes into the controller ok:

string[] values = new string[] {"123", "Pie", "456", "Cake"};

I need to convert it into a dictionary:

Dictionary<int,string> Deserts = new Dictionary<int,string>() { {123, "Pie"}, {456, "Cake"} };

I tried:

values.ToDictionary(v => int.Parse(v), v => values.IndexOf(v) + 1);

but that gives an error at runtime. Index not found.

Answer Source

using a for loop

var deserts = new Dictionary<int,string>();
for (var i = 0; i < values.Length; i += 2) {
    deserts.Add(int.Parse(values[i]), values[i+1]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download