Reputation: 151
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
Reputation: 156
you can make it shorter this way
<h1>@Model.Details.Sum(x=> Convert.ToInt32(x.Amt))</h1>
Upvotes: 2
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