我正在尝试从列表中获取一些值。但我想确保如果 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>.GetValueOrDefault
或null-coalescing
不污染太多代码的东西?
var vmBusinessDays = new BusinessDay()
{
Jan = businessDays[1].GetValueOrDefault(),
Feb = businessDays[1]?? 0
}
我知道Dictionary<TKey, TValue>.TryGetValue
,但它会复制代码行以将输出值设置为每个属性。