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.
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.
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:
You can do the second easily with LINQ:
var newDict = myDict.ToDictionary( kvp => kvp.Key, kvp => kvp.Value-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