/// <summary> /// Tests for an overlap of given date ranges /// </summary> /// <param name="TestEndPoints">Set to true if you want to count the date range end points as an overlap and false if you don't care if the end points overlap.</param> /// <param name="Ranges">The set of date ranges that you want to test.</param> /// <returns>True if there is an overlap of the ranges. False if there is no overlap.</returns> public static bool HasOverlap(bool TestEndPoints, params DateOverlap[] Ranges) { if (Ranges.Count() < 2) { throw new Exception("Ranges count must be greater than 1"); } List <DateOverlap> Dates = new List <DateOverlap>(); List <DateOverlap> WhiteSpace = new List <DateOverlap>(); Dates.AddRange(Ranges); Dates = Dates.OrderBy(r => r.Start).ToList(); Parallel.For(0, Dates.Count - 1, i => { if (Dates[i].End < Dates[i + 1].Start) { WhiteSpace.Add(new DateOverlap(Dates[i].End, Dates[i + 1].Start)); } }); TimeSpan total = Ranges.Max(r => r.End) - Ranges.Min(r => r.Start); TimeSpan sum = new TimeSpan(); foreach (DateOverlap r in Ranges) { sum += r.Span; } foreach (DateOverlap r in WhiteSpace) { sum += r.Span; } if (sum < total) { return(false); } if (sum > total) { return(true); } if (!TestEndPoints) { return(false); } var query = from a in Dates join b in Dates on a.Start equals b.End select a; return(query.Count() > 0); }