Dictionary ContainsKey并在一个函数中获取值
有没有办法调用Dictionary
一次来找到一个键的值? 现在我正在打两个电话。
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(this IDictionary dictionary, TKey key, TValue fallback = default(TValue)) { TValue result; return dictionary.TryGetValue(key, out result) ? result : fallback; } }
然后可以用于:
Dictionary 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”条件,我会认为你只是将问题转移到了稍微进一步的空检查。