简体   繁体   中英

Check if date range is sequential in c# except Saturday and Sunday

I want to determine if a list of datetimes are sequential.

Also if the datetimes missing from the list are Saturday or Sunday, the list also

Examples

Is Sequential

1.

  • 2020-11-02 ( Mo )
  • 2020-10-30 ( Fr )
  • 2020-10-29 ( Th )
  • 2020-10-28 ( We )
  • 2020-10-27 ( Tu )
  • 2020-11-06 ( Fr )
  • 2020-11-05 ( Th )
  • 2020-11-04 ( We )
  • 2020-11-03 ( Tu )
  • 2020-11-02 ( Mo )

Is Not Sequential

3.

  • 2020-11-03 ( Tu )
  • 2020-10-30 ( Fr )
  • 2020-10-29 ( Th )
  • 2020-10-28 ( We )
  • 2020-10-27 ( Tu )
  • 2020-11-06 ( Fr )
  • 2020-11-05 ( Th )
  • 2020-11-04 ( We )
  • 2020-11-02 ( Mo )

I'm missing the saturday , sunday logic. This is my snippet

  public static bool IsSequential(IEnumerable<DateTime> dates)
    {
        var startDate = dates.FirstOrDefault();

        return dates
            .Select((d, i) => new {Date = d, Index = i})
            .All(d => (d.Date - startDate).Days == d.Index);
    }

You might do something like this. It should work when dates are ordered both ascending and descending.

public static bool IsSequential(this IList<DateTime> dates)
{
    DateTime currentDate;
    DateTime nextDate;
    for (int index = 0; index < dates.Count - 1; index++)
    {
        currentDate = dates[index];
        nextDate = dates[index + 1];

        var dayDiff = Math.Abs((nextDate.Date - currentDate.Date).Days);
        var areSequentialDates = dayDiff == 1 ||
            (dayDiff == 3 && (currentDate.DayOfWeek == DayOfWeek.Friday || nextDate.DayOfWeek == DayOfWeek.Friday));

        if (!areSequentialDates)
            return false;
    }

    return true;
}

Another approach, assuming descending:

public static bool IsSequential(IEnumerable<DateTime> dates)
{
    if (dates != null)
    {
        DateTime nextDate = dates.FirstOrDefault().Date;
        foreach (DateTime dt in dates)
        {
            if (!dt.Date.Equals(nextDate))
            {
                return false;
            }
            nextDate = dt.Date.AddDays(dt.DayOfWeek == DayOfWeek.Monday ? -3 : -1);
        }
    }            
    return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM