如何从列表返回筛选结果并统计指定ScheduleId下各Line员工总数
按Work Line分组统计同一ScheduleId下员工总数实现方案
需求说明
数据库表包含字段:ScheduleId、Line、OperatorId、Shift、Function
需要从全量记录中,筛选出同一ScheduleId下的员工数据,按Line(Work Line)分组后,统计每组的员工总数(需排除同一员工在同一Line下的重复记录)
现有代码问题
当前代码仅按ScheduleId去重后循环生成表格,仅展示单条记录的Line和OperatorId,未实现分组统计逻辑。
推荐实现方式:后端ViewModel处理(MVC最佳实践)
1. 定义统计模型
在项目中添加用于统计的模型类:
public class LineEmployeeCount { public string Line { get; set; } public int EmployeeTotal { get; set; } }
2. 更新页面ViewModel
修改页面ViewModel,新增统计集合属性:
public class YourPageViewModel { // 原有全量数据属性 public List<Schedule> AllSchedules { get; set; } // 新增:按ScheduleId分组的统计结果,Key为ScheduleId,Value为该Schedule下的Line统计列表 public Dictionary<int, List<LineEmployeeCount>> ScheduleLineEmployeeStats { get; set; } }
3. 在Controller中处理数据逻辑
在Action中完成数据分组统计:
public IActionResult YourPage() { var allSchedules = _dbContext.Schedules.ToList(); // 从数据库获取全量记录 // 按ScheduleId分组,再对每个Schedule下的记录按Line分组,统计去重后的OperatorId数量 var stats = allSchedules .GroupBy(s => s.ScheduleId) .ToDictionary( g => g.Key, g => g.GroupBy(s => s.Line) .Select(lineGroup => new LineEmployeeCount { Line = lineGroup.Key, // 统计不同的OperatorId数量,避免重复计数 EmployeeTotal = lineGroup.Select(s => s.OperatorId).Distinct().Count() }) .ToList() ); var viewModel = new YourPageViewModel { AllSchedules = allSchedules, ScheduleLineEmployeeStats = stats }; return View(viewModel); }
4. 修改.cshtml视图代码
@model YourPageViewModel @foreach (var scheduleStats in Model.ScheduleLineEmployeeStats) { <h3>ScheduleId: @scheduleStats.Key</h3> <table border="1"> <thead> <tr> <th>Work Line</th> <th>员工总数</th> </tr> </thead> <tbody> @foreach (var lineStat in scheduleStats.Value) { <tr> <td>@lineStat.Line</td> <td>@lineStat.EmployeeTotal</td> </tr> } </tbody> </table> <br /> }
临时方案:视图层直接处理(仅用于快速调试)
如果不想修改后端,可直接在视图中处理逻辑(不推荐,会增加视图层负担):
@foreach (var scheduleGroup in Model.AllSchedules.GroupBy(x => x.ScheduleId)) { <h3>ScheduleId: @scheduleGroup.Key</h3> <table border="1"> <thead> <tr> <th>Work Line</th> <th>员工总数</th> </tr> </thead> <tbody> @foreach (var lineGroup in scheduleGroup.GroupBy(x => x.Line)) { <tr> <td>@lineGroup.Key</td> <td>@lineGroup.Select(x => x.OperatorId).Distinct().Count()</td> </tr> } </tbody> </table> <br /> }
内容的提问来源于stack exchange,提问作者Maria
相关产品推荐
相关产品推荐

