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)
where, if someKey
is not present, then someDefaultValue
is returned.
In C#, there's TryGetValue()
which is kinda similar:
var lookupValue;
if(!somedict.TryGetValue(someKey, lookupValue))
lookupValue = someDefaultValue;
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;
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()
?
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;
}
Of course you might actually want an exception if key is null
since that is always an invalid key for a dictionary.
This can now be simplified to the following with C# 7.0 inline out variable declarations.
return key == null || !dictionary.TryGetValue(key, out var value)
? defaultValue
: value;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With