C#使用Linq统计布尔值 筛选Present为false次数≥2的考勤项
解决方案
你现有代码只完成了近3天缺勤记录的基础过滤,没有做分组计数和阈值筛选,按以下逻辑补充即可:
- 先过滤出近3天所有
Present=false的原始考勤记录 - 按你需要统计的维度(通常是学生ID,可根据业务加班级、教师等字段做联合分组)分组,统计每组的记录数,保留记录数≥2的分组
- 从原始缺勤记录中筛选出属于上述合格分组的条目,映射为响应类型后按更新时间倒序排列
返回符合条件的缺勤明细代码
// 过滤近3天缺勤原始记录 var recentAbsentRecords = attentdance .Where(a => !a.Present && a.UpdatedOn >= DateTime.Now.AddDays(-3)); // 筛选出近3天缺勤次数≥2的统计维度键,这里以按学生ID统计为例 var qualifiedKeys = recentAbsentRecords .GroupBy(a => a.StudentId) // 如需按多维度统计,分组改为 .GroupBy(a => new {a.StudentId, a.ClassRoomId}) .Where(g => g.Count() >= 2) .Select(g => g.Key) .ToHashSet(); // 组装最终结果 var attentdanceList = recentAbsentRecords .Where(a => qualifiedKeys.Contains(a.StudentId)) // 多维度分组时判断条件改为 qualifiedKeys.Contains(new {a.StudentId, a.ClassRoomId}) .OrderByDescending(a => a.UpdatedOn) .Select(attent => new AttentdanceResponse { Id = attent.RowKey, SchoolId = attent.PartitionKey, StudentId = attent.StudentId, ClassRoomId = attent.ClassRoomId, TeacherId = attent.TeacherId, Latitude = attent.Latitude, Longitude = attent.Longitude, Present = attent.Present, Timestamp = (DateTime)attent.UpdatedOn }) .ToList();
如果需要直接返回缺勤统计结果(带False计数),用以下代码
var attentdanceStatList = attentdance .Where(a => !a.Present && a.UpdatedOn >= DateTime.Now.AddDays(-3)) .GroupBy(a => new {a.StudentId, a.ClassRoomId, a.TeacherId, a.PartitionKey}) .Where(g => g.Count() >= 2) .OrderByDescending(g => g.Max(x => x.UpdatedOn)) .Select(g => new { SchoolId = g.Key.PartitionKey, StudentId = g.Key.StudentId, ClassRoomId = g.Key.ClassRoomId, TeacherId = g.Key.TeacherId, FalseCount = g.Count(), LatestRecordTime = g.Max(x => x.UpdatedOn) }) .ToList();
调整说明
- 分组字段可根据业务需求灵活修改:如果只需要统计学生个人的缺勤次数,仅保留
StudentId作为分组键即可;如果需要区分不同班级、不同授课老师的考勤场景,把对应字段加入分组匿名对象即可 - 合格分组键用
ToHashSet()存储,相比普通List在数据量较大时Contains判断性能更高 - 如果需要按自然日统计(即从3天前的0点开始算),把时间条件里的
DateTime.Now.AddDays(-3)替换为DateTime.Today.AddDays(-3)即可,避免当前时分秒导致的时间范围偏差
内容的提问来源于stack exchange,提问作者Mayank saini
相关产品推荐
相关产品推荐

