如何验证列表中所有DateTime日期属于同一月份和年份?
如何判断C#中日期列表的所有日期是否属于同一月份和年份
要实现这个需求,核心就是检查列表里所有日期的年份和月份是否完全一致,下面提供几种实用的实现方式:
基础LINQ实现(简洁直观)
用LINQ的All方法可以快速完成判断,代码简洁易懂,适合大多数场景:
public static bool AreAllDatesInSameMonthAndYear(IEnumerable<DateTime> dates) { if (dates == null) throw new ArgumentNullException(nameof(dates)); // 处理空列表:这里默认返回true,你也可以根据需求改成false或抛出异常 if (!dates.Any()) return true; var firstDate = dates.First(); return dates.All(d => d.Year == firstDate.Year && d.Month == firstDate.Month); }
测试示例
把你提供的测试用例代入,就能得到预期结果:
// 应返回true IEnumerable<DateTime> dates1 = new List<DateTime>() { new DateTime(2022, 11, 30), new DateTime(2022, 11, 14), new DateTime(2022, 11, 2) }; Console.WriteLine(AreAllDatesInSameMonthAndYear(dates1)); // 输出 True // 应返回false IEnumerable<DateTime> dates2 = new List<DateTime>() { new DateTime(2022, 11, 30), new DateTime(2022, 11, 14), new DateTime(2022, 10, 2) }; Console.WriteLine(AreAllDatesInSameMonthAndYear(dates2)); // 输出 False
高性能遍历实现(适合大数据量)
如果你的日期列表非常大,上面的LINQ实现会遍历两次列表(一次First一次All),可以改用枚举器只遍历一次,提升性能:
public static bool AreAllDatesInSameMonthAndYear(IEnumerable<DateTime> dates) { if (dates == null) throw new ArgumentNullException(nameof(dates)); using var enumerator = dates.GetEnumerator(); // 空列表处理 if (!enumerator.MoveNext()) return true; var targetYear = enumerator.Current.Year; var targetMonth = enumerator.Current.Month; while (enumerator.MoveNext()) { if (enumerator.Current.Year != targetYear || enumerator.Current.Month != targetMonth) return false; } return true; }
这个版本从列表中取第一个日期的年月后,逐个检查后续日期,一旦发现不一致就立刻返回false,无需遍历整个列表,效率更高。
内容的提问来源于stack exchange,提问作者Tom el Safadi
相关产品推荐
相关产品推荐

