Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unifiy two arrays in a dictionary?

Tags:

c#

If you have two arrays string[] a and int[] b how can you get a Dictionary<string,int> 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++)
{
    vals.Add(a[i],b[i]);
}
like image 521
selion Avatar asked May 26 '11 03:05

selion


3 Answers

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.

like image 184
Anthony Pegram Avatar answered Oct 20 '22 11:10

Anthony Pegram


If this is .Net 4, then you can do the following:

var result = a.Zip(b, (first, second) => new {first, second})
    .ToDictionary(val => val.first, val => val.second);

Without Zip, you can also do this:

var result = Enumerable.Range(0, a.Length).ToDictionary(i => a[i], i => b[i]);
like image 32
Chris Pitman Avatar answered Oct 20 '22 13:10

Chris Pitman


Using ToDictionary:

        int idx = 0;
        var dict = b.ToDictionary(d => a[idx++]);
like image 1
Sergiy Avatar answered Oct 20 '22 11:10

Sergiy