I have a collection of periods [FromDate, ToDate].
I would know whether there is any overlap between a given period and the periods in the collection.>
If FromDate <= ToDate always holds true for your Period objects, you can define a helper extension method OverlapsWith as follows:
public static bool OverlapsWith(this Period a, Period b)
{
return !(b.ToDate <= a.FromDate || a.ToDate <= b.FromDate);
}
To illustrate what's going on, let's look at the two cases where there is no overlap between a and b:
// a
// |-----------------|
// |--------| |-----------|
// b1 b2
You can check the above condition against this diagram. Since the diagram shows the cases where no overlap occurs, but the method really ought to test for overlap, the condition needs to be negated. It could be simplified to the following:
b.ToDate > a.FromDate && a.ToDate > b.FromDate
When you use this method in a LINQ query, it turns out very easy to understand:
Periods.Any(period => period.OverlapsWith(periodToCheck))