重构LINQ操作避免重复代码:优化日期筛选逻辑
优雅重构C#日期筛选逻辑代码
核心需求:根据参考时间referenceDate的小时数决定筛选规则:
- 若小时≥20,选取
daysToCut中大于当日日期的项 - 否则选取
daysToCut中大于等于当日日期的项 - 若没有符合条件的项,取
daysToCut的最小值
原代码实现
using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { // 示例日期:07/02 // 待选日期:10, 15, 20, 25 // 规则:晚8点后只选次日及以后的日期;晚8点前可包含当日 int nextDayToTake = 0; var daysToCut = new List<int>{10, 15, 20, 25}; var referenceDate = DateTime.Now; // 输出10,因为当日是07/02 // var referenceDate = new DateTime(2023, 02, 10, 20, 00, 00); // 输出15,因为当日是10号且时间≥20点 if (referenceDate.Hour >= 20) { nextDayToTake = daysToCut.Any(x => x > referenceDate.Day) ? daysToCut.First(x => x > referenceDate.Day) : daysToCut.Min(); } else { nextDayToTake = daysToCut.Any(x => x >= referenceDate.Day) ? daysToCut.First(x => x >= referenceDate.Day) : daysToCut.Min(); } Console.WriteLine(nextDayToTake); } }
尝试的三元运算符实现(可读性较差)
var daysToCut = new List<int>{10, 15, 20, 25}; var referenceDate = DateTime.Now; // var referenceDate = new DateTime(2023, 02, 10, 20, 00, 00); var nextDayToTake = referenceDate.Hour >= 20 ? daysToCut.Any(x => x > referenceDate.Day) ? daysToCut.First(x => x > referenceDate.Day) : daysToCut.Min() : daysToCut.Any(x => x >= referenceDate.Day) ? daysToCut.First(x => x >= referenceDate.Day) : daysToCut.Min(); Console.WriteLine(nextDayToTake);
优雅重构方案
通过提取变量简化条件判断,复用LINQ查询逻辑,让代码结构更清晰:
using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { var daysToCut = new List<int>{10, 15, 20, 25}; var referenceDate = DateTime.Now; // var referenceDate = new DateTime(2023, 02, 10, 20, 00, 00); int referenceDay = referenceDate.Day; bool isAfter8PM = referenceDate.Hour >= 20; // 根据时间筛选符合条件的日期 var validDays = daysToCut.Where(day => isAfter8PM ? day > referenceDay : day >= referenceDay); // 取第一个符合条件的日期,无符合项则取最小值 int nextDayToTake = validDays.DefaultIfEmpty(daysToCut.Min()).First(); Console.WriteLine(nextDayToTake); } }
重构说明
- 提取变量:把
referenceDate.Day和时间判断结果存为变量,避免重复调用和重复判断,提升可读性 - 复用筛选逻辑:通过
Where统一处理两种筛选条件,减少代码冗余 - 简化空值处理:用
DefaultIfEmpty直接指定无符合项时的默认值(即列表最小值),替代原代码中Any+First的组合,逻辑更简洁
内容的提问来源于stack exchange,提问作者drinnari
相关产品推荐
相关产品推荐

