C# Dictionary: Getting Values

In C#, you can use the indexer of a Dictionary to retrieve its corresponding value. There are two ways to retrieve the value:

  1. Access values using square brackets and keys.
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("key1", "value1");
dict.Add("key2", "value2");

string value = dict["key1"];
Console.WriteLine(value);  // 输出: value1
  1. Use the TryGetValue method to retrieve a value, which returns a boolean value indicating whether the value was successfully retrieved.
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("key1", "value1");
dict.Add("key2", "value2");

string value;
if (dict.TryGetValue("key1", out value))
{
    Console.WriteLine(value);  // 输出: value1
}

Note: Accessing a value using square brackets or the TryGetValue method will either throw a KeyNotFoundException if the key does not exist or return false. Therefore, it is recommended to check if the key exists in the dictionary before using these methods, which can be done using the ContainsKey method.

bannerAds