I want to be able to give a key-value pair list as a parameter in a function, and then add this list to a dictionary, (I also want to control, if the key already exists in the dictionary) how can I do this? Maybe with a for each loop, but Add() function takes 2 arguments.
public void func(List<KeyValuePair<string, int>> pairs)
{
foreach ( var pair in pairs)
{
dictionary.Add(pair); // this is not working
}
}
>Solution :
You cannot straight add a KeyValuePair<TKey,TValue> to a dictionary, you need to add as a key and a value:
dictionary.Add(pair.Key, pair.Value);
If you want to overwrite an existing key with a new value, or insert the new key/value (an upsert operation):
dictionary[pair.Key] = pair.Value;
If you only want to add new key/value pairs (do not disturb/overwrite existing data), you can check if the key exists first:
if(!dict.ContainsKey(pair.Key)) dictionary.Add(pair.Key, pair.Value);
Or, if you have it available in your version of .net, you can TryAdd:
dict.TryAdd(pair.Key, pair.Value) //returns false and does not add if the key exists
In either of these latter two (ContainsKey returning true if the items exists, or TryAdd returning false if the item exists) you can use that boolean to decide what to do – merging the data in the dictionary already with the data in the incoming item for example