Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decrement all int values in Dictionary

I have a Dictionary<string,int> and I simply want to decrement the value in my dictionary by one.

I have this but not sure if its best practice.

foreach (KeyValuePair<string, int> i in EPCs)
{
   EPCs[i.Key] = i.Value - 1;
}

UPDATE: The reason I am trying to decrement the value is becase the value is a index number relating to a position. When I remove something from the dictionary I then have to decrement that index number in the dictionary. There may be a better way.

like image 682
Jon Avatar asked Jan 22 '23 02:01

Jon


2 Answers

Your existing code is an entirely appropriate way to decrement all of the values in a dictionary.

If you wanted to create a new dictionary, you could use LINQ:

EPCs = EPCs.ToDictionary(p => p.Key, p => p.Value - 1);

This will, however, create an entirely new Dictionary<string, int> instance, rather than modifying the existing instance in place. However, since you tagged your question with linq, I figured I would offer the one way (that I'm aware of) where LINQ could solve your problem.

like image 128
Adam Robinson Avatar answered Jan 24 '23 17:01

Adam Robinson


I think this is completely appropriate.

But since you asked the question, what are you concerned about that may not be reasonable about this kind of code?

You should realize that you have two options to do what you're looking for, either:

  1. Modify the existing dictionary by visiting each entry (which your code does), or
  2. Create a new dictionary with the computed values you want.

You can do the second easily with LINQ:

var newDict = myDict.ToDictionary( kvp => kvp.Key, kvp => kvp.Value-1 );
like image 21
LBushkin Avatar answered Jan 24 '23 17:01

LBushkin