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)
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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);
}
Method 2
you can make it shorter this way
<h1>@Model.Details.Sum(x=> Convert.ToInt32(x.Amt))</h1>
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0