Home > Back-end >  How to tell if dates are sequential or not excluding weekends
How to tell if dates are sequential or not excluding weekends

Time:02-24

I have a method that will return true/false if a list of dates is sequential or not. I need to exclude weekends, so if the list is Thu 5, Fri 6, Mon 9 Tue 10 then its true (sequential).

My method is -

public static bool IsSequential(List<DateTime> timeList)
{
    //populate list..
    return timeList.Zip(timeList.Skip(1),
                                     (a, b) => b.Date == a.Date.AddDays(1))
                                .All(x => x);
}

CodePudding user response:

Just AddDays based on the DayOfWeek, so if Monday add 3 days if not only add 1.

So instead of only a.Date.AddDays(1)

Extend it to this:

a.Date.AddDays((b.Date.DayOfWeek == DayOfWeek.Monday ? 3 : 1))

public static bool IsSequential(List<DateTime> timeList)
{
    //populate list..
    return timeList.Zip(timeList.Skip(1),(a, b) => b.Date == a.Date.AddDays((b.Date.DayOfWeek == DayOfWeek.Monday ? 3 : 1))).All(x => x);
}

https://dotnetfiddle.net/CtRk6K

CodePudding user response:

You could try something like this:

Just check the days and compare it with an element of the list.

public static bool IsSequential(List<DateTime> timeList)
{
    // less than 2? it's sequential.
    if (timeList.Count < 2)
        return true;

    // an array of valid DayOfWeek's
    var validDays = new DayOfWeek[] { DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday };

    // the first date to start with
    var startDate = timeList.First();

    // index of the source list
    int i = 0;
    // an offset from the startDate
    int dayCounter = 0;

    // loop until all timeList items are compared.
    while (i < timeList.Count)
    {
        // get the next date to check.
        var newDate = startDate.AddDays(dayCounter);

        // check if it needs to be present in the timeList
        if (validDays.Contains(newDate.DayOfWeek))
        {
            // if they are not equal, there is a gap.
            if (timeList[i] != newDate)
                return false;

            // increase the index for the next item. (only on a valid DayOfWeek)
            i  ;
        }
        // increase the offset from the startDate
        dayCounter  ;
    }
    // all are equal.
    return true;
}

It would be possible with difficult linq queries, but I think this is more easy to debug.

  •  Tags:  
  • c#
  • Related