ConcurrentDictionarydict = new ConcurrentDictionary (); dict.TryAdd("A", 1); dict.TryAdd("B", 2); dict.TryAdd("C", 3); dict.AddOrUpdate("A", 5, (key, oldValue) => oldValue + 1); // Output: A: 6, B: 2, C: 3 foreach (var kvp in dict) { Console.WriteLine(kvp.Key + ": " + kvp.Value); }
ConcurrentDictionaryIn this example, we use the AddOrReplace method to update the value associated with key "A" to 5. This method is useful when we want to strictly replace the existing value with the new one. If the key does not exist, it will throw an exception. The ConcurrentDictionary class is part of the System.Collections.Concurrent namespace in the .NET framework.dict = new ConcurrentDictionary (); dict.TryAdd("A", 1); dict.TryAdd("B", 2); dict.TryAdd("C", 3); dict.AddOrReplace("A", 5); // Output: A: 5, B: 2, C: 3 foreach (var kvp in dict) { Console.WriteLine(kvp.Key + ": " + kvp.Value); }