Given a DateRange I need to return a list of Start and EndDates that overlaps the given period.
what is the best way to do it? Thanks for your time in advance.
Are you looking for dates that are completely within the provided period, or only partially?
Completely within the range:
var overlapped =
from period in bookedPeriods
where period.StartDate >= startDate && period.EndDate <= endDate
select new OverlappedPeriod { StartDate = period.StartDate, EndDate = period.EndDate };
overlappedPeriods = overlapped.ToList();
Partially overlapping:
var overlapped =
from period in bookedPeriods
where (period.StartDate >= startDate && period.EndDate <= endDate)
|| (period.EndDate >= startDate && period.EndDate <= endDate)
|| (period.StartDate <= startDate && period.EndDate >= startDate)
|| (period.StartDate <= startDate && period.EndDate >= endDate)
select new OverlappedPeriod
{
StartDate = new DateTime(Math.Max(period.StartDate.Ticks, startDate.Ticks)),
EndDate = new DateTime(Math.Min(period.EndDate.Ticks, endDate.Ticks))
};
overlappedPeriods = overlapped.ToList();