如何使用LINQ按月份筛选日期范围内的当月考勤数据
问题说明
学习LINQ使用过程中,在实现按月份筛选日期数据时遇到阻碍,目标是筛选出当前月份的对应考勤数据。
当前编写的实现代码如下:
var attentdanceList = from attent in attentdance orderby attent.UpdatedOn descending where attent.Present is (false) select 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 };
当前代码运行输出结果:
问题分析
现有代码仅实现了两个逻辑:
- 按
UpdatedOn字段倒序排序 - 筛选
Present为false的缺勤记录
核心缺失点是没有添加当前月份的时间过滤条件,同时存在两处可优化的写法问题: - LINQ查询建议将
where过滤条件放在orderby之前,先缩小待排序的数据范围,减少不必要的排序计算,提升执行效率 attent.Present is (false)属于冗余模式匹配写法,布尔类型直接判断相等即可,可读性更高
修复实现
优先推荐使用时间范围做筛选,这种写法在对接数据库(如EF Core查询关系型数据库)时可以命中时间字段的索引,执行效率远高于单独提取年、月属性做判断的写法,同时完全兼容内存集合查询场景。
修复后的完整代码:
// 预先计算当前月份的时间边界:当月1号0点、下月1号0点 DateTime currentTime = DateTime.Now; DateTime monthStart = new DateTime(currentTime.Year, currentTime.Month, 1); DateTime monthEnd = monthStart.AddMonths(1); var attentdanceList = from attent in attentdance // 先执行过滤:筛选缺勤记录 + 时间落在当前月份范围内 where attent.Present == false where attent.UpdatedOn >= monthStart where attent.UpdatedOn < monthEnd // 过滤完成后再做排序、结果投影 orderby attent.UpdatedOn descending select 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 };
提示:如果业务中存储的时间是UTC时间,将
DateTime.Now替换为DateTime.UtcNow即可,保证筛选时间和存储时间的时区一致。
如果是纯内存集合查询、不需要考虑数据库索引性能,也可以直接在过滤条件中匹配年和月:
where attent.UpdatedOn.Year == currentTime.Year && attent.UpdatedOn.Month == currentTime.Month
内容的提问来源于stack exchange,提问作者Mayank saini
相关产品推荐
相关产品推荐

