总结c# foreach中的结果

  • 本文关键字:结果 foreach 总结 c#
  • 更新时间 :
  • 英文 :


我有一个对象,它使用foreach遍历一个列表,并返回我正在访问的对象的值。

根据具体情况,对象返回一个count = 10,例如

我需要总结所有这些记录的值,我尝试如下,但它没有返回任何值。

如果我删除+=并只留下=,我只检索第一个记录。

我怎样才能总结所有的记录?

public decimal? ValesDisponiveis
{
get
{
decimal? informacaoRetorno = null;
if (ValeCreditos != null)
{
foreach (ValeCredito vale in ValeCreditos)
{
informacaoRetorno += vale.ValesDisponiveis;
}
}
return informacaoRetorno;
}
} 

问题是:

decimal? informacaoRetorno = null;

而不是使用:

decimal? informacaoRetorno = 0;

或者在这种情况下最好不要为空,因为初始化为0:

decimal informacaoRetorno = 0;

编辑

如评论中所述,如果您仍然希望null作为有效结果,如果IEnumerable为空,您仍然可以执行以下操作:

if (ValeCreditos == null)
return null;

return ValeCreditors.Sum(x => x.ValesDisponiveis);

如果ValesDisponiveis已经有正确的基类型,

假设您想要返回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上返回null或空ValeCreditos,否则返回项目之和。

最新更新