How to retrieve a value from a C# dictionary using a key?

In C#, you can retrieve values by key using the TryGetValue method of a Dictionary or by directly using the [key] index operator.

  1. Utilize the TryGetValue method:
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("key1", 100);
dict.Add("key2", 200);

int value;
if (dict.TryGetValue("key1", out value))
{
    Console.WriteLine("Value for key1: " + value);
}
  1. Utilize the indexing operator [key]:
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("key1", 100);
dict.Add("key2", 200);

int value = dict["key1"];
Console.WriteLine("Value for key1: " + value);

Note: When using the indexing operator [key], if the specified key does not exist in the dictionary, a KeyNotFoundException exception will be thrown. It is therefore best to use the TryGetValue method to avoid potential exceptions.

Leave a Reply 0

Your email address will not be published. Required fields are marked *