Dictionaries
A dictionary is a
Key-Valuepair.The
Keymust be unique.
Usage
// Declaring a dictionary and adding values
Dictionary<int, string> myDictionary = new Dictionary<int, string>();
myDictionary.Add(1, "A");
myDictionary.Add(2, "B");
// This will generate a runtime error
myDictionary.Add(2, "C");Data Retrieval
// The value of the Key = 3 is retireved to the string variable 's'.
bool result = myDictionary.TryGetValue(3, out string s);
// If the specified key exists, 'true' is returned and the value is retrieved
if (result == true)
{
Console.WriteLine("Value = " + s);
}
// If the key doesn't exist, 'false' is returned and nothing is retrieved
else
{
Console.WriteLine("Value not found");
}Last updated