add a key-value pair to a map in csharp

To add a key-value pair to a map (in C# called dictionary), you can use the Add method. Here's an example:

main.cs
Dictionary<string, int> myMap = new Dictionary<string, int>();
myMap.Add("apple", 3);
myMap.Add("banana", 5);
110 chars
4 lines

In this example, we create a dictionary that maps string keys to integer values. Then, we use the Add method to add two key-value pairs to the dictionary: "apple" maps to 3 and "banana" maps to 5.

Alternatively, you can also use the [] operator to add or update a key-value pair:

main.cs
myMap["orange"] = 2;
21 chars
2 lines

This line of code adds a new key-value pair to the dictionary, where "orange" maps to 2. If "orange" already existed in the dictionary, its value would have been overwritten.

gistlibby LogSnag