How to unifiy two arrays in a dictionary?

后端 未结 4 1227
说谎
说谎 2020-12-25 13:09

If you have two arrays string[] a and int[] b how can you get a Dictionary from it most efficiently and with least c

4条回答
  •  独厮守ぢ
    2020-12-25 14:04

    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();
    
    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.

提交回复
热议问题