所以我正在做一个cshtml网站,我似乎无法弄清楚如何总结数据库和foreach中每一行的产品!
var db = Database.Open("TestDB");
var getData = "SELECT * FROM Test";
然后
@foreach (var get in db.Query(getData)) {
<a>@get.kg</a>
<a>@get.set</a>
<a>@get.rep</a>
//So this row gives me the product of each row in the database
@(get.kg * get.set * get.rep)
<br>
}
但我想总结所有总数!不知道该怎么做!
答案 0 :(得分:2)
我的cshtml有点生疏,但我认为这样可以解决这个问题:
@{ var sumTotalWeight = 0 }
@foreach (var get in db.Query(getData)) {
<a>@get.kg</a>
<a>@get.set</a>
<a>@get.rep</a>
@{
var totalWeight = @get.kg * @get.set * @get.rep;
sumTotalWeight += totalWeight
}
<br>
}
@sumTotalWeight
实际上处理这个问题的更好方法是在你的代码中进行计算和数学运算并将你的值放在ViewBag中 - 这样可以保持你的UI代码更清晰:
var query = @"SELECT kg, set, rep, kg*set*rep as 'total' FROM Test";
using (var db = Database.Open("TestDB"))
{
// .ToArray() to materialize the query;
ViewBag.Items = db.Query(query).ToArray();
// you might need to cast to ints (i'm not sure)
ViewBag.SumTotal = ViewBag.Items.Sum(i => (i.total));
}
然后在cshtml
:
@foreach (var item in ViewBag.Items) {
<a>@item.kg</a>
<a>@item.set</a>
<a>@item.rep</a>
@item.total
<br>
}
Total: @ViewBag.SumTotal