开发者

Decrement all int values in Dictionary

I have a Dictionary<string,int> and I simply want to decrement the value in my dictio开发者_JAVA百科nary 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:

  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 );


This is not a direct answer, but instead of decrementing it for each item you could just store an offset and decrement it on the fly when getting an item, either as specialized class or just in the code in general.


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

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

Use it like this:

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

It's not exactly any cleaner than what you had before but a little more compact though. The Reactive Extensions have a similar operator in System.Interactive called Do.


Your code is perfectly fine given the circumstances (Dictionary<string,int>).

If you need high performance using something else than a dictionary might be a better choice in the long run.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜