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.
Is Not Sequential
3.
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.