Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to tell if dates are sequential or not excluding weekends

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);
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading