开发者

How to unifiy two arrays in a dictionary?

开发者 https://www.devze.com 2023-03-08 05:55 出处:网络
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

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++开发者_StackOverflow中文版)
{
    vals.Add(a[i],b[i]);
}


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.


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]);


Using ToDictionary:

        int idx = 0;
        var dict = b.ToDictionary(d => a[idx++]);


var result = a.ToDictionary(x => x, x => b[a.IndexOf(x)]);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号