Daniel Jørgensen
Daniel Jørgensen

Reputation: 1202

Check what a value of a specifc key is in a Dictionary

Im new to Dictionaries, so i have this basic question.

I have a dictionary like this:

Dictionary<string, string> usersLastStamp = checking.checkLastStamp();

How can i do a if statement that checks if a value of a specific key is something?

Like this:

if(usersLastStamp.the_value_of_key("theKey") == "someValue")
{
    //Do something
}

I've taken a look at TryGetValue, but im not quite sure how to use it directly like the above in a if statement.

Upvotes: 0

Views: 92

Answers (4)

vc 74
vc 74

Reputation: 38179

usersLastStamp["theKey"] will throw an exception if the key is not present in the dictionary (as specified here). You can use TryGetValue instead and combine it with short circuit evaluation:

string value = null;
if (usersLastStamp.TryGetValue("theKey", out value) && (value == "someValue"))
{
}

Upvotes: 6

artm
artm

Reputation: 8584

You can use either

string someVal = "";

if (myDict.ContainsKey(someKey))
 someVal = myDict[someKey];

or

string someVal = "";
if (myDict.TryGetValue(somekey, out someVal))

and then your if:

if (someVal == "someValue")

TryGetValue takes an out parameter, returns a bool, retruns true and updates the parameter if the key exists in the dictionary, if key doesn't exist in the dictionary returns false. Or you have to check if the key exists in the dictionary and only if it exists then take the value from it.

Upvotes: 0

Rajeev Kumar
Rajeev Kumar

Reputation: 4963

You could try

if(usersLastStamp["theKey"] != null && usersLastStamp["theKey"] == "SomeValue")
{
      // Your cdoe writes here
}

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062780

Folks have already answered the TryGetValue approach, but as an alternative: if it is an option, you could also consider using StringDictionary instead of Dictionary<string,string> - this returns null in the case that there is no value at that key, so you can just use:

if(usersLastStamp["theKey"] == "someValue")

without any risk of it erroring.

Upvotes: 1

Related Questions