繁体   English   中英

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

[英]Dictionary ContainsKey and get value in one function

有没有办法调用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吗?

您可以使用TryGetValue

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

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

选中的答案是正确答案。 这是为提供者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

为了您的目的,这可能应该这样做。 就像你在问题中提到的那样,将所有内容(null或值)全部放入对象中:

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

要么..

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

我想,你可以做这样的事情(或写一个更清晰的扩展方法)。

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

我不确定我是否会特别高兴使用它,但是通过结合null和你的“Found”条件,我会认为你只是将问题转移到一个空的检查稍微下线。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM