Fill Keys and values of a Dictionary<K, V> using arrays in C#
I have two equally sized arrays, arrayKeys and arrayValues filled with data, respectively for Keys and Values, and an empty Dictionary<K, V>
(myDictionary). I would like to assign as Keys and Values of the Dictionary the elements in each开发者_运维百科 array. I know that this can be done by using the following code:
for(i=0:i<arrayKeys.Lenght;i++)
{
myDictionary.Add(arrayKeys[i], arrayValue[i]);
}
but I would like to know whether is there any way to perform the assignment as follows:
myDictionary.Keys = arrayKeys;
myDictionary.Values = arrayValues;
maybe by using lambdas with the ToDictionary method. Thanks in advance
Francesco
You can write
myDictionary = keys.Zip(values, (k, v) => new { k, v })
.ToDictionary(o => o.k, o => o.v);
You can't assign them directly, but you can use some variant of:
var myDict = arrayKeys.Select((item, i) => new { Key = item, Value = arrayValues[i] })
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
No, you cannot do that.
Because of the way that Dictionary
works, you have to insert each KeyValuePair<K, V>
at the same time (since the location of the value is determined by the hash of the key).
精彩评论