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.

 

More tutorials

How is the usage of JSONObject in Android?(Opens in a new browser tab)

How can I include new entries in a Python dictionary?(Opens in a new browser tab)

How do you call AutoResetEvent in C#?(Opens in a new browser tab)

get pandas DataFrame from an API endpoint that lacks order?(Opens in a new browser tab)

How can properties files be read in Python?(Opens in a new browser tab)

How is WinForms implemented in C#?(Opens in a new browser tab)

Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds