Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing a numerical value in a dictionary

Tags:

c#

dictionary

I'm using the code below to either increment or insert a value in a dictionary. If the key I'm incrementing doesn't exist I'd like to set its value to 1.

 public void IncrementCount(Dictionary<int, int> someDictionary, int id)  {        int currentCount;      if (someDictionary.TryGetValue(id, out currentCount))      {          someDictionary[id] = currentCount + 1;      }      else      {          someDictionary[id] = 1;      }  } 

Is this an appropriate way of doing so?

like image 682
KingNestor Avatar asked Aug 20 '11 15:08

KingNestor


People also ask

How do you increment the value of a dictionary?

By using the get() function we can increment a dictionary value and this method takes the key value as a parameter and it will check the condition if the key does not contain in the dictionary it will return the default value. If the given key exists in a dictionary then it will always return the value of the key.


1 Answers

Your code is fine. But here's a way to simplify in a way that doesn't require branching in your code:

int currentCount;  // currentCount will be zero if the key id doesn't exist.. someDictionary.TryGetValue(id, out currentCount);   someDictionary[id] = currentCount + 1; 

This relies on the fact that the TryGetValue method sets value to the default value of its type if the key doesn't exist. In your case, the default value of int is 0, which is exactly what you want.


UPD. Starting from C# 7.0 this snippet can be shortened using out variables:

// declare variable right where it's passed someDictionary.TryGetValue(id, out var currentCount);  someDictionary[id] = currentCount + 1; 
like image 95
Ani Avatar answered Sep 22 '22 09:09

Ani