MVC4-如何求和foreach列表的结果? [英] MVC4 - How can I sum a result of a foreach list?
本文介绍了MVC4-如何求和foreach列表的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的项目跟踪每个员工使用的休假时间.我想显示在foreach结果上方使用的小时数总和.休假索引会提取所选员工的数据.
My project tracks vacation hours used per employee. I would like to display the Sum of hours used above the foreach result. The vacation index retireves the data for the selected employee.
模型1
public class Employee
{
public int EmployeeID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public virtual ICollection<Vacation> Vacation { get; set; }
}
模型2
public class Vacation
{
public int VacationID { get; set; }
public int EmployeeID { get; set; }
[DataType(DataType.Date)]
public DateTime EventDate { get; set; }
public int Hours { get; set; }
public virtual Employee Employee { get; set; }
}
模型2的控制器
public class VacationController : Controller
{
private Context db = new Context();
//
// GET: /Vacation/
public ActionResult Index([Bind(Prefix = "id")]int employeeId)
{
var Employee = db.Employee.Find(employeeId);
if (Employee != null)
{
return View(Employee);
}
return HttpNotFound();
}
查看
<table>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Employee.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.EventDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Hours)
</td>
<td>
@Html.DisplayFor(modelItem => item.Notes)
</td>
</tr>
}
</table>
推荐答案
您可以使用以下表达式计算小时总和:
You can calculate the sum of hours with the following expression:
var sum = Model.Vacation.Sum(vacation => vacation.Hours);
您可以将其添加到视图的顶部:
You could add it at the top of your view:
Sum of hours: @Model.Vacation.Sum(vacation => vacation.Hours)
这篇关于MVC4-如何求和foreach列表的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文