Chen Chen Chen Chen - 22 days ago 12
C# Question

Modify a dictionary in a for loop in C#

I am experienced in C/C++ but pretty much a newbie in C#. My question is pretty simple. Say we have a hash table with integer keys and values and we want to increment all the values in the hash table by 1. We prefer to accomplish this with O(1) extra memory.

Below is one solution, which, to my opinion, is somehow ugly. Is there other way to make it looks more decent?

Dictionary<int, int> dict = new Dictionary<int, int>();
for (int i = 0; i < dict.Count; ++i)
{
dict[dict.Keys.ElementAt(i)]++;
}


PS: I heard that
foreach
is read-only in C#. But, is there any way like
for(auto it& : dict) it.second++
in C++ that I can use to still accomplish this task in C#?

Answer

Dictionary<,> itself doesn't provide a good way of doing this - because updating the value associated with a key counts as a change that invalidates any iterator. ConcurrentDictionary<,> does allow this though, and even has an AddOrUpdate method which will help you:

using System;
using System.Linq;
using System.Collections.Concurrent;

class Test
{
    static void Main()
    {
        var dict = new ConcurrentDictionary<int, int>
        {
            [10] = 15,
            [20] = 5,
            [30] = 10
        };
        foreach (var key in dict.Keys)
        {
            dict.AddOrUpdate(key, 0, (k, v) => v + 1);
        }
        Console.WriteLine(string.Join("\r\n", dict.Select(kp => $"{kp.Key}={kp.Value}")));
    }
}