gpt4 book ai didi

c# - 字典或列表的 GetValueOrDefault 或空合并

转载 作者:太空宇宙 更新时间:2023-11-03 10:49:35 25 4
gpt4 key购买 nike

我正在尝试从列表中获取一些值。但我想确保如果 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 , 但它会复制用于为每个属性设置输出值的代码行。

最佳答案

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

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

关于c# - 字典或列表的 GetValueOrDefault 或空合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22023838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com