Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increase Value of Dictionary at a specified Key

Tags:

c#

dictionary

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
     }
 }
like image 963
Yagiz Ozturk Avatar asked Mar 16 '11 11:03

Yagiz Ozturk


People also ask

How can a dictionary increase its value?

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.

How do you increase the value of a key in python?

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.

Can you change the value of a key in a dictionary?

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.

Which method will modify the value of a key in a dictionary?

We use the pop method to change the key value name.


2 Answers

Why are you using LINQ fot this, and not just the Indexer of the Dictionary?

Something like

MyDictionary[person.personID] += 1;
like image 81
Adriaan Stander Avatar answered Nov 13 '22 10:11

Adriaan Stander


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.

like image 42
Øyvind Bråthen Avatar answered Nov 13 '22 09:11

Øyvind Bråthen