2

我正在尝试从列表中获取一些值。但我想确保如果 key 不存在,它将返回默认值0而不是抛出异常。

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]
    [..]
};

如何使用类似Nullable<T>.GetValueOrDefaultnull-coalescing不污染太多代码的东西?

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

我知道Dictionary<TKey, TValue>.TryGetValue,但它会复制代码行以将输出值设置为每个属性。

4

2 回答 2

3

您可以定义自己的扩展方法:

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

然后你可以像这样使用它:

var vmBusinessDays = new BusinessDay()
{
    Jan = businessDays.GetValueOrDefault(1),
    Feb = businessDays.GetValueOrDefault(2)
}
于 2014-02-25T19:18:43.143 回答
2

在 C# 7.0 或更高版本中,您可以使用以下一种衬里:

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

如果要在字典中创建键值对,可以执行以下操作:

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

或者

public Item GetOrCreate(Key key) => 
            TryGetValue(key, out var item) ? item : dictionary[key] = new Item();
于 2022-01-12T20:36:34.130 回答