Home > Mobile >  Best way to assign key-value pairs to a dictionary from 2 arrays in c#
Best way to assign key-value pairs to a dictionary from 2 arrays in c#

Time:03-20

    Dictionary<long, long> test = new Dictionary<long, long>();

    long[] keyArray= new long[] { 1, 2, 3, 4 };
    long[] valueArray= new long[] { 4, 3, 2, 1 };

Question 1:

I tried

    for (var i = 0; i < keyArray.Length; i  )
    {
        test.Add(new KeyValuePair<long, long>(keyArray[i], valueArray[i]));
    }

But, I get

There is no argument given that corresponds to the required formal parameter 'value' of 'Dictionary<long, long>.Add(long, long)'

I couldn't figure out why.

Question 2 How to make these assignments more scalable? For example, my arrays can be much bigger. Would the same method be logical for that case?

CodePudding user response:

Dictionary<TKey,TValue>.Add(TKey, TValue) requires 2 parameters first being key, second being value, not one KeyValuePair, so you need to change your code slightly:

for (var i = 0; i < keyArray.Length; i  )
{
    test.Add(keyArray[i], valueArray[i]);
}

Note that Add will throw in case if you will try to add an already existing key. If you anticipate duplicate keys and it is ok to silently overwrite value with later one you can just use indexer:

for (var i = 0; i < keyArray.Length; i  )
{
    test[keyArray[i]] = valueArray[i];
}

CodePudding user response:

LINQ variant:

var test = keyArray.Zip(valueArray).ToDictionary(x => x.First, x => x.Second);
  • Related