Home > database >  Summarize results within a C# foreach
Summarize results within a C# foreach

Time:10-27

I have an object that traverses a list using foreach and returns the value of the object I'm accessing.

Depending on the case, the object returns a count = 10, for example.

I need to summarize the values ​​of all these records and I'm trying as follows, but it returns nothing.

If I remove the = and leave only =, I only retrieve the first record.

How can I summarize all the records?

public decimal? ValesDisponiveis
{
    get
    {
        decimal? informacaoRetorno = null;

        if (ValeCreditos != null)
        {
            foreach (ValeCredito vale in ValeCreditos)
            {
                informacaoRetorno  = vale.ValesDisponiveis;
            }
        }
        return informacaoRetorno;
    }
} 

CodePudding user response:

The problem is:

decimal? informacaoRetorno = null;

Instead use:

decimal? informacaoRetorno = 0;

Or in this case better without nullable because initialization with 0:

decimal informacaoRetorno = 0;

Edit

As mentioned in the comments if you still want null as a valid result if the IEnumerable is null you still can do the following:

if (ValeCreditos == null)
        return null;
    
return ValeCreditors.Sum(x => x.ValesDisponiveis);

If ValesDisponiveis has already the correct base type.

CodePudding user response:

Assuming that you want to return null in case there's no items to be summed (say, when ValeCreditos is empty) you should check for 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;
    }
}

This code returns null on null or empty ValeCreditos and sum of items otherwise.

  •  Tags:  
  • c#
  • Related