selion selion -3 years ago 116
C# Question

How to unifiy two arrays in a dictionary?

If you have two arrays

string[] a
int[] b
how can you get a
from it most efficiently and with least code possible? Assume that they contain the same number of elements.

For example, is this the best way?

Dictionary<string,int> vals = new Dictionary<string,int>();
for(int i = 0; i < size; i++)

Answer Source

If your goal is to match at positions within the sequences, you can use Enumerable.Zip.

int[] myInts = { 1, 2 };
string[] myStrings = { "foo", "bar"};

var dictionary = myStrings.Zip(myInts, (s, i) => new { s, i })
                          .ToDictionary(item => item.s, item => item.i);

And since you are working with arrays, writing it "longhand" really isn't all that long. However, you want to validate beforehand the arrays truly are equal in length.

var dictionary = new Dictionary<string, int>();

for (int index = 0; index < myInts.Length; index++)
    dictionary.Add(myStrings[index], myInts[index]);

Usually, Linq can result in more expressive, easier to understand code. In this case, it's arguable the opposite is true.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download