我阅读了一些与C#函数相关的问题/答案来计算工作日(从周一到周五的日子);有些使用扩展代码来实现这一点。
我有一个超过 50,000 行的数据表,我需要一种有效的方法来计算这些信息。
根据@MiBols 的回答,一个更有效的解决方案是使用 HashSet<DateTime>
而不是 List<DateTime>
然后在 O(1)
中进行搜索:
/// <summary> Get working days between two dates (Excluding a list of dates - Holidays) </summary>
/// <param name="dtmCurrent">Current date time</param>
/// <param name="dtmFinishDate">Finish date time</param>
/// <param name="excludedDates">Collection of dates to exclude (Holidays)</param>
public static int fwGetWorkingDays(this DateTime dtmCurrent, DateTime dtmFinishDate,
HashSet<DateTime> excludedDates)
{
Func<DateTime, bool> workDay = currentDate => (
currentDate.DayOfWeek == DayOfWeek.Saturday ||
currentDate.DayOfWeek == DayOfWeek.Sunday ||
excludedDates.Contains(currentDate.Date));
return Enumerable.Range(0, 1 + (dtmFinishDate - dtmCurrent).Days)
.Count(intDay => workDay(dtmCurrent.AddDays(intDay)));
}
我是一名优秀的程序员,十分优秀!