我有一个使用foreach遍历列表的对象,并返回要访问的对象的值。
例如,根据情况,对象返回一个count = 10。
我需要总结所有这些记录的值,我正在尝试如下,但它没有返回任何内容。
如果删除+=而只保留=,则只检索第一条记录。
我如何总结所有的记录?
public decimal? ValesDisponiveis
{
get
{
decimal? informacaoRetorno = null;
if (ValeCreditos != null)
{
foreach (ValeCredito vale in ValeCreditos)
{
informacaoRetorno += vale.ValesDisponiveis;
}
}
return informacaoRetorno;
}
} 发布于 2021-10-26 15:11:54
问题是:
decimal? informacaoRetorno = null;相反,请使用:
decimal? informacaoRetorno = 0;或者在这种情况下,最好不使用空,因为初始化时使用0:
decimal informacaoRetorno = 0;编辑
如注释中所述,如果仍然希望null作为有效结果,如果IEnumerable为null,则仍然可以执行以下操作:
if (ValeCreditos == null)
return null;
return ValeCreditors.Sum(x => x.ValesDisponiveis);如果ValesDisponiveis已经具有正确的基类型。
发布于 2021-10-26 15:24:03
假设您想返回null,如果没有要加和的项(例如,当ValeCreditos为空时),则应该检查HasValue
public decimal? ValesDisponiveis
{
get
{
decimal? informacaoRetorno = null;
if (ValeCreditos != null)
{
foreach (ValeCredito vale in ValeCreditos)
{
if (informacaoRetorno.HasValue) // business as usual: just add
informacaoRetorno += vale.ValesDisponiveis;
else // null + value == null, that's why we assign
informacaoRetorno = vale.ValesDisponiveis;
}
}
return informacaoRetorno;
}
}此代码返回null on null或空ValeCreditos,否则返回项之和。
https://stackoverflow.com/questions/69725579
复制相似问题