Modify a dictionary in a for loop in C# -
i experienced in c/c++ pretty newbie in c#. question pretty simple. have hash table integer keys , values , want increment values in hash table 1. prefer accomplish o(1) memory.
below 1 solution, which, opinion, somehow ugly. there other way make looks more decent?
dictionary<int, int> dict = new dictionary<int, int>(); (int = 0; < dict.count; ++i) { dict[dict.keys.elementat(i)]++; }
ps: heard foreach
read-only in c#. but, there way for(auto it& : dict) it.second++
in c++ can use still accomplish task in c#?
dictionary<,>
doesn't provide way of doing - because updating value associated key counts change invalidates iterator. concurrentdictionary<,>
does allow though, , has addorupdate
method 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}"))); } }
Comments
Post a Comment