C#Dictionary相当于Python的get()方法 [英] C# Dictionary equivalent to Python's get() method
问题描述
在Python中,如果我有一个dict,并且我想从一个dict中获取一个可能不存在密钥的值,那么我将执行以下操作:
In Python, if I have a dict, and I want to get a value from a dict where the key might not be present I'd do something like:
lookupValue = somedict.get(someKey, someDefaultValue)
其中,如果 someKey
不存在,则返回 someDefaultValue
。
where, if someKey
is not present, then someDefaultValue
is returned.
在C#中,有 TryGetValue()
有点类似:
In C#, there's TryGetValue()
which is kinda similar:
var lookupValue;
if(!somedict.TryGetValue(someKey, lookupValue))
lookupValue = someDefaultValue;
一个有趣的是,如果 someKey
是 null
然后一个异常被抛出,所以你进行一个空值检查:
One gotcha with this though is that if someKey
is null
then an exception gets thrown, so you put in a null-check:
var lookupValue = someDefaultValue;
if (someKey != null && !somedict.TryGetValue(someKey, lookupValue))
lookupValue = someDefaultValue;
哪个,TBH,是icky(3行为一个dict查找?)有一个更简洁即1线)的方式,就像Python的 get()
?
Which, TBH, is icky (3 lines for a dict lookup?) Is there a more concise (ie 1-line) way that is much like Python's get()
?
推荐答案
以下是使用 TryGetValue
的正确方法。请注意,您不能在调用 TryGetValue
之前将返回值设置为默认值,并将其返回为 TryGetValue
将重置它如果没有找到密钥,则为默认值。
Here's the correct way to use TryGetValue
. Note that you can not set the return value to the default before calling TryGetValue
and just return it as TryGetValue
will reset it to it's default value if the key is not found.
public static TValue GetOrDefault<TKey, TValue>(
this IDictionary<TKey, TValue> dictionary,
TKey key,
TValue defaultValue)
{
TValue value;
if(key == null || !dictionary.TryGetValue(key, out value))
return defaultValue;
return value;
}
当然,如果key是 null
,因为这对于字典来说总是无效的键。
Of course you might actually want an exception if key is null
since that is always an invalid key for a dictionary.
这篇关于C#Dictionary相当于Python的get()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!