Scanning a list and adding values [closed]

1

I am scanning a list and taking certain values, adding and saving it. In the first run I get the value, add it to an 'x' variable, and go to the second execution ...

I get the value that was added to 'x' and sum to the value of the second execution.

However, in this second execution the value instead of being added, is replaced by the value of the second execution.

  public async Task<IHttpActionResult> GetNotas()
  {
    foreach (var us in resultQuery.ToPagedList(page, pageSize))
        {
            var nota = await GetNotaAsync(us);
            CalcularTotais(nota);
            itens.Add(nota);
        }
    return Ok(itens);
   }



 private static void CalcularTotais(NotaViewModel nota)
    {
        decimal totalBaseCalculo = 0;
        decimal totalIss = 0;
        decimal totalLiquido = 0;

        if (!nota.IsIssRetido || nota.Situacao == SituacaoNota.Cancelada) {
            totalBaseCalculo += nota.BaseCalculo;
            totalIss += nota.Iss;
            totalLiquido += nota.Liquido;
        }
    }

Note: this method is inside a foreach of a public method.

    
asked by anonymous 02.04.2018 / 13:44

1 answer

0

You are not returning anything, and when you do foreach the sum is within the scope of the CalcularTotais method, variables are being reset every time you call them:

decimal totalBaseCalculo = 0;
decimal totalIss = 0;
decimal totalLiquido = 0;

You can use LINQ SUM to add the values from within your list without the need for a foreach :

class TestClass
{
    static void Main(string[] args)
    {
       //Essa é sua lista
       List<NotaViewModel> notas = new List<NotaViewModel>;

       //População da lista

       decimal totalBaseCalculo = notas.Sum(nota => nota.BaseCalculo);
       decimal totalIss = notas.Sum(nota => nota.Iss);
       decimal totalLiquido = notas.Sum(nota => nota.Liquido);
    }
}
    
02.04.2018 / 14:45