Decrease all int values ​​in a dictionary

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

I have this, but not sure its best practice.

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

UPDATE: The reason I'm trying to decrease the value is because the value is an index number related to the position. When I delete something from the dictionary, I have to decrease this index number in the dictionary. Perhaps the best way.

+4
source share
5 answers

Existing code is a completely suitable way to reduce all values ​​in a dictionary.

If you want to create a new dictionary, you can use LINQ:

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

This, however, will create an entirely new instance of Dictionary<string, int> instead of modifying the existing instance in place. However, since you tagged your question with linq , I decided that I was suggesting one of the ways (what I know) where LINQ can solve your problem.

+5
source

I think this is quite appropriate.

But since you asked the question, what is bothering you, it might not be reasonable for such code?

You must understand that you have two options to do what you are looking for, either:

  • Modify an existing dictionary by visiting each entry (what your code does) or
  • Create a new dictionary with calculated values.

You can do the second with LINQ:

 var newDict = myDict.ToDictionary( kvp => kvp.Key, kvp => kvp.Value-1 ); 
+2
source

This is not a direct answer, but instead of decrementing it for each element, you can simply save the offset and reduce it on the fly when you receive the element, either as a specialized class, or only in the code at all.

+2
source

You can write a little for each enumerator that takes an action and executes it for each element:

  public static void ForEach<T>(this IEnumerable<T> source, Action<T> action) { foreach (T element in source) { action(element); } } 

Use it as follows:

  EPCs.ForEach(x => EPCs[x.Key] = x.Value -1); 

It is not quite clean than yours before, but a little more compact. Reactive Extensions have a similar statement in System.Interactive called Do

0
source

Your code works fine under circumstances ( Dictionary<string,int>).

If you need high performance using something other than a dictionary, a better choice in the long run.

0
source

Source: https://habr.com/ru/post/1309329/


All Articles