Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetValueOrDefault or null-coalescing for Dictionary or List

I'm trying to get some values from a list. But I want to assure that if key doesn't exist, it will return a default value 0 instead of throwing exception.

var businessDays = days.Where(x => x.Year == year).ToDictionary(x => x.Month, x => x.Qty);

var vmBusinessDays = new BusinessDay()
{
    Jan = businessDays[1],
    Feb = businessDays[2],
    Mar = businessDays[3],
    Apr = businessDays[4],
    May = businessDays[5]
    [..]
};

How is possible to use something like Nullable<T>.GetValueOrDefault or null-coalescing without polluting too much the code?

var vmBusinessDays = new BusinessDay()
{
    Jan = businessDays[1].GetValueOrDefault(),
    Feb = businessDays[1]?? 0
}

I'm aware of Dictionary<TKey, TValue>.TryGetValue, but it will duplicate code lines for setting output value to each property.

like image 483
Andre Figueiredo Avatar asked Dec 17 '25 13:12

Andre Figueiredo


2 Answers

You can define your own extension method:

public static class DictionaryExtensions
{
    public static TValue GetValueOrDefault<TKey, TValue>(
        this IDictionary<TKey, TValue> dict, TKey key)
    {
        TValue val;
        if (dict.TryGetValue(key, out val))
            return val;
        return default(TValue);
    }
}

You could then use it like so:

var vmBusinessDays = new BusinessDay()
{
    Jan = businessDays.GetValueOrDefault(1),
    Feb = businessDays.GetValueOrDefault(2)
}
like image 122
Douglas Avatar answered Dec 20 '25 02:12

Douglas


In C# 7.0 or above you can use the following one liner:

public Item GetOrDefault(Key key) => 
    TryGetValue(key, out var item) ? item : default(Item);

If you want to create the key value pair in the dictionary, you can do the following:

public Item GetOrCreate(Key key) => 
        TryGetValue(key, out var item) ? item : dictionary[key] = default(Item);

or

public Item GetOrCreate(Key key) => 
            TryGetValue(key, out var item) ? item : dictionary[key] = new Item();
like image 21
Greg Avatar answered Dec 20 '25 02:12

Greg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!