To create a mapping in C#, you can use the Dictionary class. Here’s an example:
Dictionary<string, int> map = new Dictionary<string, int>();
map.Add("apple", 1);
map.Add("banana", 2);
map.Add("orange", 3);Console.WriteLine(map["apple"]); // Output: 1
Console.WriteLine(map["banana"]); // Output: 2
Console.WriteLine(map["orange"]); // Output: 3
In this example, we create a Dictionary that maps strings to integers. We add three key-value pairs to the dictionary using the Add method. Then, we retrieve the values from the dictionary using the keys and print them to the console.
Note that if you try to retrieve a value using a key that doesn’t exist in the dictionary, you’ll get a KeyNotFoundException. To avoid this, you can use the TryGetValue method, which returns a boolean indicating whether the key was found and an out parameter containing the value:
int value;
if (map.TryGetValue("pear", out value))
{
Console.WriteLine(value);
}
else
{
Console.WriteLine("Key not found");
}
