find the value associated with a key in a map in csharp

In C#, a map can be represented using the Dictionary<TKey, TValue> class. You can use the TryGetValue method of the dictionary to retrieve the value associated with a given key. Here's an example:

main.cs
Dictionary<string, int> map = new Dictionary<string, int>();
map.Add("apple", 1);
map.Add("banana", 2);
map.Add("pear", 3);

int value;
if (map.TryGetValue("banana", out value))
{
    Console.WriteLine("The value associated with 'banana' is {0}.", value);
}
else
{
    Console.WriteLine("'banana' is not a key in the dictionary.");
}
334 chars
15 lines

In this example, we create a dictionary map that associates strings with integers. We add three key-value pairs to the map. Then, we use the TryGetValue method to attempt to retrieve the value associated with the key "banana". If the key is found, then value will be set to the associated value, and we print out that value. If the key is not found, then we print out a message indicating that fact.

related categories

gistlibby LogSnag