2014-10-07 55 views
0

我是新的字典,所以我有這個基本的問題。檢查一個特定的密鑰在一個字典中的值是什麼

我有這樣一本字典:

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

我怎樣才能做一個if語句來檢查,如果一個特定鍵的值是什麼?

像這樣:

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

我已經採取一看TryGetValue,但我不是很清楚如何直接在if語句使用它像上面。

+0

你可以谷歌它...如何從字典 – mybirthname 2014-10-07 10:31:20

回答

6

usersLastStamp["theKey"]將拋出一個異常,如果該鍵不存在在詞典中(如指定here)。您可以使用TryGetValue,而不是與short circuit evaluation結合起來:

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

你可以嘗試

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

您可以使用

string someVal = ""; 

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

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

,然後你是否:

if (someVal == "someValue") 

TryGetVal如果密鑰存在於字典中,如果密鑰不存在於字典中,則返回false,則ue接受一個out參數,返回一個bool,重新返回true並更新參數。或者你必須檢查密鑰是否存在於字典中,並且只有在密鑰存在的情況下才能從中獲取值。

+0

價值不應該是ContainsKey? – 2014-10-08 13:27:39

+0

@MarcGravell你是對的,糾正它。 – artm 2014-10-08 22:23:32

1

鄉親們已經回答了TryGetValue的做法,但作爲一種替代方案:如果它是一個選項,你可以也考慮使用StringDictionary,而不是Dictionary<string,string> - 這將返回null的情況下,有在該鍵的值,所以你可以使用:

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

沒有任何錯誤的風險。

+1

我很樂意反饋這個downvote;這似乎是一個完全合理的方法。 – 2014-10-07 10:39:33

+0

我實際上也喜歡關於這個downvote的一些反饋。與TryGetValue approuch IMO相比,這看起來更具可讀性。 – 2014-10-07 13:56:27

+0

@DanielJørgensen我認爲當我指出他們現在被刪除的答案中存在一些主要問題時,實際上只是有人不高興。我懷疑我會生存下去,p – 2014-10-07 14:26:42

相關問題