Fill in the keys and values ​​of the dictionary <K, V> using arrays in C #

I have two arrays of the same size, arrayKeys and arrayValues , filled with data, respectively, for the keys and values, and an empty Dictionary<K, V>( MyDictionary strong>). I would like to assign elements in each array as keys and dictionary values. I know that this can be done using the following code:

for(i=0:i<arrayKeys.Lenght;i++)
{
   myDictionary.Add(arrayKeys[i], arrayValue[i]);
}

but I would like to know if there is a way to accomplish the assignment as follows:

myDictionary.Keys = arrayKeys;
myDictionary.Values = arrayValues;

possibly using lambdas with the ToDictionary method. thanks in advance

Francesco

+3
source share
3 answers

You can write

myDictionary = keys.Zip(values, (k, v) => new { k, v })
                   .ToDictionary(o => o.k, o => o.v);
+4
source

, - :

var myDict = arrayKeys.Select((item, i) => new { Key = item, Value = arrayValues[i] })
    .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
+4

, .

- , Dictionary, KeyValuePair<K, V> ( ).

0
source

All Articles