2013-06-30 49 views
6

有沒有辦法一次爲Dictionary<string, int>找到一個鍵的值?現在我正在打兩個電話。詞典包含鍵和在一個函數中獲取值

if(_dictionary.ContainsKey("key") { 
int _value = _dictionary["key"]; 
} 

我想要做它喜歡:

object _value = _dictionary["key"] 
//but this one is throwing exception if there is no such key 

我想如果返回null不存在這樣的鍵或一個電話獲得的價值?

回答

9

,如果它包含指定鍵可以使用TryGetValue

int value; 
bool exists = _dictionary.TryGetValue("key", out value); 

TryGetValue返回true,否則爲false。

+2

如果字典包含帶有該鍵的元素,則TryGetValue將返回true,否則返回false。 – Femaref

+0

如果他有一個像{「key」,0}這樣的鍵/值對,並且他試圖從一個不存在的鍵中獲取該值,那麼該int值將爲0。 – terrybozzio

+0

@terrybozzio在這種情況下'exists'將會是'false' –

1

這應該可能做到這一點,爲您的目的。 就像你問的問題,讓所有一氣呵成,null或值,到一個對象:

object obj = _dictionary.ContainsKey("key") ? _dictionary["key"] as object : null; 

或..

int? result = _dictionary.ContainsKey("key") ? _dictionary["key"] : (int?)null; 
+0

這是'O(| keys |)'。我們可以做得更好。 – jason

+0

「鍵」是一個字典中作爲鍵的示例,而不是 - 獲取鍵 - – terrybozzio

+0

我明白這一點。但是'Enumerable.Where'會對所有的鍵進行線性搜索。這就是爲什麼它的鍵數量是線性的。通過'|鍵|'表示鍵的數量給出了'O(|鍵|)'。 – jason

7

所選答案正確的。這是供應商user2535489以實現他的想法的正確方法:

public static class DictionaryExtensions 
{ 
    public static TValue GetValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue fallback = default(TValue)) 
    { 
     TValue result; 

     return dictionary.TryGetValue(key, out result) ? result : fallback; 
    } 
} 

然後可以與使用:

Dictionary<string, int> aDictionary; 
// Imagine this is not empty 
var value = aDictionary.GetValue("TheKey"); // Returns 0 if the key isn't present 
var valueFallback = aDictionary.GetValue("TheKey", 10); // Returns 10 if the key isn't present 
+0

如果您從字典或後備中獲得價值,仍然無法知道。我沒有看到像這樣包裝'TryGetValue'的任何價值。 – spender

+1

你是對的。但是如果用戶關心密鑰是否在字典中,用戶可以選擇使用'TryGetValue'。如果他不在乎並且想要一個班輪,那只是語法糖。因爲我覺得我失去控制,我個人不會使用我的主張。這純粹是爲了討論。 –

0

我想,你可以做這樣的事情(或寫更清晰的擴展方法)。

 object _value = _dictionary.ContainsKey(myString) ? _dictionary[myString] : (int?)null; 

我不知道我會用特別高興的是,雖然,結合空和你「發現」的條件,我還以爲你只是換擋的問題,以空校驗略微進一步下線。

相關問題