Dictionary ContainsKey并在一个函数中获取值

ief*_*fpw 7 c# dictionary

有没有办法调用Dictionary<string, int>一次来找到一个键的值?现在我正在打两个电话.

if(_dictionary.ContainsKey("key") {
 int _value = _dictionary["key"];
}
Run Code Online (Sandbox Code Playgroud)

我想这样做:

object _value = _dictionary["key"] 
//but this one is throwing exception if there is no such key
Run Code Online (Sandbox Code Playgroud)

如果没有这样的密钥或者通过一次调用获取值,我会想要null吗?

Tom*_*dee 10

您可以使用 TryGetValue

int value;
bool exists = _dictionary.TryGetValue("key", out value);
Run Code Online (Sandbox Code Playgroud)

TryGetValue 如果它包含指定的键,则返回true,否则返回false.

  • 如果字典包含具有该键的元素,则"TryGetValue"将返回true,否则返回false. (2认同)

Sim*_*ger 8

选中的答案是正确答案.这是为提供者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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后可以用于:

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
Run Code Online (Sandbox Code Playgroud)