C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Cat, dog: We use the Add method to map the "cat" and "dog" strings to some words that indicate color.
Foreach: We loop over all keys and values in the map. We access each KeyValuePair in the map in the foreach loop.
KeyValuePairTryGetValue: This is the best method to access a value in the map from a key. It returns false if the key does not exist.
TryGetValueC# program that uses Dictionary as map
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Use Dictionary as a map.
var map = new Dictionary<string, string>();
// ... Add some keys and values.
map.Add("cat", "orange");
map.Add("dog", "brown");
// ... Loop over the map.
foreach (var pair in map)
{
string key = pair.Key;
string value = pair.Value;
Console.WriteLine(key + "/" + value);
}
// ... Get value at a known key.
string result = map["cat"];
Console.WriteLine(result);
// ... Use TryGetValue to safely look up a value in the map.
string mapValue;
if (map.TryGetValue("dog", out mapValue))
{
Console.WriteLine(mapValue);
}
}
}
Output
cat/orange
dog/brown
orange
brown