To get the value associated with a key in a dictionary in C#, you can use the indexer or the `TryGetValue` method of the `Dictionary
We can get the value associated with a key in a dictionary in C# using the indexer. This example demonstrates how to retrieve the value for a specific key and print it.
For example,
using System.Collections.Generic;
.myDictionary
with integer keys and string values.using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Declare and initialize a dictionary
Dictionary<int, string> myDictionary = new Dictionary<int, string>
{
{1, "One"},
{2, "Two"},
{3, "Three"}
};
// Key to get the value for
int keyToGet = 2;
// Get the value associated with the key using the indexer
string value = myDictionary[keyToGet];
// Print the value associated with the key
Console.WriteLine("The value associated with key {0} is '{1}'.", keyToGet, value);
}
}
The value associated with key 2 is 'Two'.
We can get the value associated with a key in a dictionary in C# using the `TryGetValue` method. This example demonstrates how to safely retrieve the value for a specific key and print it if it exists.
For example,
using System.Collections.Generic;
.myDictionary
with integer keys and string values.using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Declare and initialize a dictionary
Dictionary<int, string> myDictionary = new Dictionary<int, string>
{
{1, "One"},
{2, "Two"},
{3, "Three"}
};
// Key to get the value for
int keyToGet = 4;
// Try to get the value associated with the key using the TryGetValue method
if (myDictionary.TryGetValue(keyToGet, out string value))
{
// Print the value associated with the key
Console.WriteLine("The value associated with key {0} is '{1}'.", keyToGet, value);
}
else
{
// Print a message if the key does not exist
Console.WriteLine("The key {0} does not exist in the dictionary.", keyToGet);
}
}
}
The key 4 does not exist in the dictionary.
In this tutorial, we learned How to Get the Value Associated with a Key in a Dictionary in C# language with well detailed examples.