Reputation: 969
I am very new to MVC 3 Razor in ASp.net. i am sending a model to a view that is tightly coupled to this model. this model has list and i want to display a SUM of particular field in that model list. is that possible and how?
Upvotes: 1
Views: 5043
Reputation: 969
Decimal D = listItem.Where(P=>P.Amount>100).Sum(P=>P.Amount);
Upvotes: 0
Reputation: 73112
I wouldn't do it in the View.
I'd do it in the ViewModel:
public class SomeViewModel
{
public ICollection<int> SomeValues { get; set; }
public int MySum { get { return SomeValues.Sum(x => x.SomeValue); } }
}
Then the view:
@Html.DisplayFor(model => model.MySum)
Alternatively you could use a generic HTML helper, made generic so you can re-use across any model which has an IEnumerable<T>
that can be aggregated.
Always try and keep your View clear of unnecessary logic.
Upvotes: 5
Reputation: 2832
This should do it, but without seeing some of your code it's hard to be exact:
@Model.YourList.Sum(p => p.PropertyNameYouWantToSum)
Upvotes: 3