ConcurrentDictionarydict = new ConcurrentDictionary (); dict.TryAdd("apple", 1); dict.TryAdd("banana", 2); dict.TryAdd("orange", 3); Console.WriteLine(dict.Count); // Output: 3
using System.Collections.Concurrent; ConcurrentDictionaryIn this example, a ConcurrentDictionary object with integer keys and string values is created and populated with three key-value pairs. The contents of the dictionary are then printed using a foreach loop, followed by the Count property to retrieve the number of pairs. The concurrent namespace is used for this example, indicating that it is part of the .NET core library.dict = new ConcurrentDictionary (); dict.TryAdd(1, "red"); dict.TryAdd(2, "green"); dict.TryAdd(3, "blue"); foreach (var item in dict) { Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value); } Console.WriteLine("Count: {0}", dict.Count); // Output: // Key: 1, Value: red // Key: 2, Value: green // Key: 3, Value: blue // Count: 3