C# Map Example

A map is also known as a dictionary or associative array in other programming languages. C# has no built-in Map type. In C#, a map is typically implemented as a dictionary (or more precisely, an instance of the Dictionary class), which provides a way to map a value with a key inside the collection. The Dictionary class is part of the System.Collections.Generic namespace and is a commonly used collection type in C#.

The concept of a C# map or dictionary is to provide a way to map a value to a key inside a collection. In a dictionary or map, every element in the collection is stored as a key-value pair, where each key maps to a corresponding value. The primary advantage of using a map or dictionary is that it provides an efficient way to retrieve values based on their keys. By using a key to look up a value, you can quickly access the associated data without having to search through the entire collection.

C# Map/Dictionary

Following is an example of how to create and use a map/dictionary in C#:

using System; using System.Collections.Generic; class MyProgram { static void Main(string[] args) { // Create a new map Dictionary<string, int> myMap = new Dictionary<string, int>(); // Add key-value pairs to the map myMap.Add("red", 100); myMap.Add("green", 200); myMap.Add("blue", 300); // Access a value by key int count = myMap["green"]; Console.WriteLine("There are {0} green colors", count); // Update a value by key myMap["blue"] = 500; // Remove a key-value pair myMap.Remove("red"); // Iterate over the keys and values in the map foreach (string key in myMap.Keys) { Console.WriteLine("{0}: {1}", key, myMap[key]); } } }
//Output: There are 200 green colors green: 200 blue: 500

In the above example, create a map called myMap using the Dictionary class. Then add three key-value pairs to the map, with "red", "green", and "blue" as keys, and 100, 200, and 300 as values, respectively.

Access C# map/dictionary values


What is C# map

You can access a value from the map using its key, like this:

int count = myMap["green"]; Console.WriteLine("There are {0} green colors", count);

You can update a value in the map by assigning a new value to its key:

myMap["blue"] = 500;

You can remove a key-value pair from the map using the Remove method:

myMap.Remove("red");

How to iterate Map/dictionary in C#

Finally, you can iterate over the keys and values in the map using a foreach loop:

foreach (string key in myMap.Keys) { Console.WriteLine("{0}: {1}", key, myMap[key]); }
//Output: green: 200 blue: 500