Search code examples
c#.netlistdictionarytrygetvalue

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.


Solution

  • 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)
    }