Sum of values in View

Asked

Viewed 69 times

0

I would like to realize a simple sum of some values in my View. I tried to accomplish it that way:

@foreach (ReceitaIndexVM receita in Model)
{
    decimal Total = 0;
    <div class="col-lg-2 col-sm-2">
        <div class="card bg-info text-white">
            <div class="card-body">
                <h6 class="card-title">Total de Receitas</h6>
                @{

                    int cont = receita.Id.ToString("C2").Count();
                    for (int i = 0; i < cont; i++)
                    {
                        Total += receita.Valor;
                    }


                }
                <h2 class="lead">@Total</h2>
            </div>
        </div>
    </div>

}

But keep this score: Resultado

I even put a Count of @recipe. Id and it brings the value of 7. What I am doing wrong?

Can you help me? Thank you!

2 answers

1

I believe you could simply do the following:

<div class="col-lg-2 col-sm-2">
    <div class="card bg-info text-white">
        <div class="card-body">
            <h6 class="card-title">Total de Receitas</h6>
            <h2 class="lead">@Model.Sum(x => x.Valor)</h2>
        </div>
    </div>
</div>

From what I understand Model of your page is already a list, so you can do the summation using Linq normally.

Using <h2 class="lead">@Model.Sum(x => x.Valor)</h2> instead of foreach and the for.

0

In this part of the code you are iterating, but you are not passing the index for the object:

for (int i = 0; i < cont; i++){
    Total += receita.Valor;
}

You can do:

for (int i = 0; i < cont; i++){
    Total += receita[i].Valor;
}

Or:

receita.foreach(item=>{
Total += item.Valor}){
  • Thanks for the help Filipe, but he accuses this error: Error CS0021 Cannot apply Indexing with [] to an Expression of type 'Receitaindexvm'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.