简体   繁体   中英

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

    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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM