Add value of a Foreach in MVC5 controller

0

I need to add the weighted the times the cycle is run and show it in builder.Append(total suma ponderados).Append(";"); , my code is as follows:

foreach (var item_ponderado in listobjetivos)
 {
   var ponderado = (item_ponderado.p.Peso_Objetivo * item_ponderado.o.calificacion / 100);
   Builder.Append(ponderado).Append(";");
 }
builder.Append(total suma ponderados).Append(";");

Let me explain, I need to add the value of the weighted variable the times that the cycle is traversed, and I can save it in a variable for example total_ponderados to show it in builder.Append(total suma ponderados).Append(";"); I do not know if I understand.

An example:

The first time the cycle was run the weighted value was 0.5 and the second time it was scanned is 1.5, the value 2 is saved in a variable to show it where mentioned above.

    
asked by ByGroxD 17.07.2017 в 20:47
source

2 answers

1

You declare it outside the foreach as decimal dTotalPonderado = 0; in the foreach within the cycle after your var ponderado = (item_ponderado.p.Peso_Objetivo * item_ponderado.o.calificacion / 100); you can put dTotalPonderado += Convert.ToDecimal(ponderado); and at the end builder.Append(dTotalPonderado ).Append(";"); and you are ready that variable dTotalWeight will contain the sum of all the weighted ones.

I hope it serves you.

    
answered by 17.07.2017 / 22:38
source
1

You could do it in the following way, I leave you the partial code, if you do not understand, you tell me:

int i =0;
List<decimal> sumatoria = new List<decimal>();
for each....

    if (i>0){
         sumatoria.Add(sumatoria[i-1]+ponderado);
    }else{
         sumatoria.Add(ponderado);
    }
    i+=1;
fin for each...

The code could be improved by using a for i instead of for each and using "smart goals [i]" instead of item_weight

I hope it serves you.

Greetings!

    
answered by 17.07.2017 в 22:30