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

In C#, you can use the TryGetValue method of a dictionary to retrieve a value based on a key. This method takes a key as a parameter and attempts to retrieve the value associated with that key from the dictionary. If the corresponding value is found, it is stored in a specified variable and true is returned. If the corresponding value is not found, false is returned.

Here is an example code:

Dictionary<string, int> myDictionary = new Dictionary<string, int>();

myDictionary.Add("key1", 1);
myDictionary.Add("key2", 2);

int value;
if (myDictionary.TryGetValue("key1", out value))
{
    // 找到了对应的值,可以使用变量value进行处理
    Console.WriteLine("找到了值:" + value);
}
else
{
    // 没有找到对应的值
    Console.WriteLine("没有找到值");
}

In the example above, a Dictionary object named myDictionary is first created and two key-value pairs are added to it. Then the TryGetValue method is used to try to retrieve a value based on “key1” – if found, the corresponding value is output, otherwise, a message indicating that the value was not found is output.

I hope this helps you!

bannerAds