总结 C# foreach 中的结果

Fav*_*eri 0 c#

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

\n

count = 10例如,根据情况,该对象返回 a 。

\n

我需要总结所有这些记录的值 \xe2\x80\x8b\xe2\x80\x8b ,我尝试如下,但它什么也不返回。

\n

如果我删除+=并仅保留=,我只检索第一条记录。

\n

如何汇总所有记录?

\n
public decimal? ValesDisponiveis\n{\n    get\n    {\n        decimal? informacaoRetorno = null;\n\n        if (ValeCreditos != null)\n        {\n            foreach (ValeCredito vale in ValeCreditos)\n            {\n                informacaoRetorno += vale.ValesDisponiveis;\n            }\n        }\n        return informacaoRetorno;\n    }\n} \n
Run Code Online (Sandbox Code Playgroud)\n

MrB*_*ank 6

问题是:

decimal? informacaoRetorno = null;
Run Code Online (Sandbox Code Playgroud)

而是使用:

decimal? informacaoRetorno = 0;
Run Code Online (Sandbox Code Playgroud)

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

decimal informacaoRetorno = 0;
Run Code Online (Sandbox Code Playgroud)

编辑

正如评论中提到的,如果您仍然想要null一个有效的结果,如果为IEnumerable空,您仍然可以执行以下操作:

if (ValeCreditos == null)
        return null;
    
return ValeCreditors.Sum(x => x.ValesDisponiveis);
Run Code Online (Sandbox Code Playgroud)

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