MVC4 - 如何汇总foreach列表的结果?

时间:2014-01-09 21:02:57

标签: c# asp.net-mvc-4

我的项目跟踪每位员工的休假时间。我想显示foreach结果上方使用的小时数。休假索引将退出所选员工的数据。

模型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>

2 个答案:

答案 0 :(得分:3)

您可以使用以下表达式计算小时数:

var sum = Model.Vacation.Sum(vacation => vacation.Hours);

您可以将其添加到视图的顶部:

Sum of hours: @Model.Vacation.Sum(vacation => vacation.Hours)

答案 1 :(得分:0)

如果您可以在控制器中设置其他字段,则可以在将列表发送到视图之前对其进行求和。

(使用LINQ扩展)

var totalHours = employee.Vacation.Aggregate((acc, val) => acc + val);