How to unifiy two arrays in a dictionary?

后端 未结 4 1216
说谎
说谎 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 13:41

    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]);
    
    0 讨论(0)
  • 2020-12-25 13:43
    var result = a.ToDictionary(x => x, x => b[a.IndexOf(x)]);
    
    0 讨论(0)
  • 2020-12-25 13:52

    Using ToDictionary:

            int idx = 0;
            var dict = b.ToDictionary(d => a[idx++]);
    
    0 讨论(0)
  • 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<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.

    0 讨论(0)
提交回复
热议问题