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.
One method would be to make use of the Rectangle class to calculate intersects. So the procedure would be to create a rectangle for each date range then use the Rectangle.Intersect( ) method.
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();
Something like this (not tested sorry):
return bookedPeriods.Where(
b => (b.StartDate > startDate && b.StartDate < endDate) ||
(b.EndDate> startDate && b.EndDate < endDate) ||
(b.StartDate < startDate && b.EndDate > endDate)
).ToList()
this piece of LINQ might help:
var overlappedPeriods = bookedPeriods.Where(p=>p.EndDate > startDate && p.StartDate < endDate);
then transform the results accordingly to your OverlappedPeriod class