检查Dictionary中特定键的值是什么

Dan*_*sen 0 c# dictionary if-statement

我是字典新手,所以我有这个基本问题.

我有一个这样的字典:

Dictionary<string, string> usersLastStamp = checking.checkLastStamp();
Run Code Online (Sandbox Code Playgroud)

如何执行if语句来检查特定键的值是否为某些值?

像这样:

if(usersLastStamp.the_value_of_key("theKey") == "someValue")
{
    //Do something
}
Run Code Online (Sandbox Code Playgroud)

我已经看了一下TryGetValue,但我不太确定如何在if语句中直接使用它.

vc *_* 74 6

usersLastStamp["theKey"]如果该键不存在在词典将抛出一个异常(如指定位置).您可以使用TryGetValue并将其与短路评估结合使用:

string value = null;
if (usersLastStamp.TryGetValue("theKey", out value) && (value == "someValue"))
{
}
Run Code Online (Sandbox Code Playgroud)