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?
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With