Lets say that I have,
Dictionary<string, int> dict = new Dictionary<string, int>();
and in there are already some items:
“A”, 1
“B”, 15
“C”, 9
….
Now, as I’m adding new ones I’m checking if the key already exist:
for(int i = 0; i<n; i++)
{
if (dict.ContainsKey(newKey[i] == true)
{
//I should add newValue to existing value(sum all of them) of existing key pair
}
else
{
dict.Add(newKey[i],newValue[i]);
}
}
How should I summarize all values for existing key, add new value to existing vale for existing key pair?
The simplest approach would be this:
This does a single “get” and then a single “put” for every key. It uses the fact that the default value of
intis 0 – whenTryGetValuereturns false,currentValuewill be set to 0, which is appropriate for a new entry.