I have a bool variable and a Dictionary. if it is true I have to increase value of my dictionary by 1 at a specified Key.
My Code :
private void Process(Person person)
{
isSendMailSuccessful = true;
if (isSendMailSuccessful)
{
MyDictionary.Where(i => i.Key == person.personID);
// I need to increase Value of that ID by 1
}
}
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.
We can also use the built-in setdefault() function to increment a dictionary's value. The working of the setdefault() function is similar to the get() function. It takes the key as an input and returns the value of that key if it exists in that dictionary. If it does not exist, then it will return the specified value.
Since keys are what dictionaries use to lookup values, you can't really change them. The closest thing you can do is to save the value associated with the old key, delete it, then add a new entry with the replacement key and the saved value.
We use the pop method to change the key value name.
Why are you using LINQ fot this, and not just the Indexer of the Dictionary?
Something like
MyDictionary[person.personID] += 1;
No reason to use LINQ here.
Assuming your dictionary is Dictionary<int,int>
, you can simply do myDictionary[person.PersonID]++;
.
You should use ContainsKey
first so verify that the key exist in the dictionary, else it will throw an exception if you try to change a dictionary entry that does not exist.
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