Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Dictionary equivalent to Python's get() method

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()?

like image 450
Adam Parkin Avatar asked Jan 29 '15 16:01

Adam Parkin


1 Answers

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;
like image 78
juharr Avatar answered Sep 30 '22 14:09

juharr