I see some problems in this code:
- The code appears to be manipulated monetary values and using the type
double
, this does not give hit, you will have rounding problems.
- Is increasing
i
twice, I can’t imagine why this is necessary.
- The data being taken does not vary.
What you can help with is this:
var listaContribuintes = PegaContribuintes(); // este método traz os contribuintes de algum lugar
Decimal subTotal = 0;
foreach (var item in listaContribuintes) {
subTotal += item.Contribuinte;
item.SubTotal = subTotal;
}
Code:
using static System.Console;
using System.Collections.Generic;
public class Program {
public static void Main() {
//as primeiras linhas abaixo é o mesmo que seria o método PegaContribuintes que eu usei no exemplo da resposta
var pessoas = new List<Pessoa> {
new Pessoa { Nome = "Elias Vieira1", Contribuinte = 31.87m },
new Pessoa { Nome = "Elias Vieira2", Contribuinte = 32.87m },
new Pessoa { Nome = "Elias Vieira3", Contribuinte = 33.87m },
new Pessoa { Nome = "Elias Vieira4", Contribuinte = 34.87m }
};
decimal subTotal = 0;
foreach (var item in pessoas) {
subTotal += item.Contribuinte;
item.SubTotal = subTotal;
WriteLine($"Nome: {item.Nome}, Contribuição: {item.Contribuinte}, SubTotal: {item.SubTotal}");
}
}
}
public class Pessoa {
public string Nome { get; set; }
public decimal Contribuinte { get; set; }
public decimal SubTotal { get; set; }
}
Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference. You have to adapt to your list, be as it is composed.
If you have more details I will update the reply.
you want the bank to return a View with this information? or this Subtotal field exists only in your application Model?
– Tobias Mesquita
Apparently, I will never be null and so your being will never end. Another thing, if you add the subtotal this way, it at the end of the for will have the last value assigned. The ideal is to take the Count from the first table and do the FOR for for it and for each value added to the subtotal, you already download in the grid, by the understood, or save in a list and then take the grid and assign this list to the datasource of the grid and bindar it.
– pnet
@Tobymosque this Subtotal field only exists in the Application.
– Randrade
Where does that come from
Contribuinte
? It does not vary. Where is your table? This excerpt and past information give no indication of how to solve the problem.– Maniero
@Renilsonandrade, I’d like to give you some advice that escapes your doubt a little. avoid declaring variables as
a
, always try to use something that better describes the variable itself, such assubTotal
.– Tobias Mesquita