我正试图从列表中获取一些值。但我想确保如果密钥不存在,它将返回默认值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
,但它会重复代码行,以便为每个属性设置输出值。
答案 0 :(得分:1)
您可以定义自己的扩展方法:
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)
}