Darshan Unadkat
Darshan Unadkat

Reputation: 151

Take sum of items in Foreach loop in ASP.NET MVC

I have a list and I want to display Sum of one of the properties.

I tried this, but it is not adding value, but it is working as string Concat.

@foreach (var item in Model.Details)
{
    int a = 0;
    a += Convert.ToInt32(item.Amt);
    @Html.DisplayTextFor(m => a)
                                                
}

Upvotes: 4

Views: 2191

Answers (2)

ibaris
ibaris

Reputation: 156

you can make it shorter this way

<h1>@Model.Details.Sum(x=> Convert.ToInt32(x.Amt))</h1>

Upvotes: 2

Alexander Petrov
Alexander Petrov

Reputation: 14231

Leave only addition in the loop. Take the rest of the code out of the loop.

@{
    int sum = 0;
    foreach (var item in Model.Details)
    {
        sum += Convert.ToInt32(item.Amt);
    }
    @Html.DisplayTextFor(m => sum)
}

Also you can use LINQ.

@{
    var sum = Model.Details.Sum(x => x.Amt);
    @Html.DisplayTextFor(m => sum);
}

Upvotes: 4

Related Questions