C#如何计算不包括特定日期的工作日(假期)

MiB*_*Bol 2 c# linq performance date datatables

我阅读了一些与 C# 中的函数相关的问题/答案来计算工作日(从星期一到星期五的天数);有些使用扩展代码来实现这一点。

我有一个包含 50,000 多行的数据表,我需要一种有效的方法来计算这些信息。

Gil*_*een 5

基于@MiBols 的回答,一个更有效的解决方案是使用 aHashSet<DateTime>而不是List<DateTime>where search is then in 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)));
}
Run Code Online (Sandbox Code Playgroud)