Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
                                                
}
like image 231
Darshan Unadkat Avatar asked Nov 15 '25 17:11

Darshan Unadkat


2 Answers

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);
}
like image 172
Alexander Petrov Avatar answered Nov 18 '25 07:11

Alexander Petrov


you can make it shorter this way

<h1>@Model.Details.Sum(x=> Convert.ToInt32(x.Amt))</h1>
like image 35
ibaris Avatar answered Nov 18 '25 06:11

ibaris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!