/// <summary> /// Explicit comparison of DateTimeRanges to be used as a delegate. /// The result is the same as the DateTimeRange.CompareTo. /// </summary> /// <param name="x">The start date of the free busy</param> /// <param name="y">The granularity of the free busy in minutes</param> /// <returns>Negative, zero or possitive number if x is smaller, equal or bigger than y respectively</returns> public static int CompareRangesByStartThenEnd( DateTimeRange x, DateTimeRange y) { if ((x == null) && (y == null)) { // If x is null and y is null, they are equal. return(0); } if (x == null) { // If x is null and y is not null, y is greater. return(-1); } if (y == null) { // If x is not null and y is null, x is greater. return(1); } int result = x.Start.CompareTo(y.Start); if (result == 0) { result = x.End.CompareTo(y.End); } #if DEBUG Debug.Assert((result == 0) == (x.CompareTo(y) == 0) && (result > 0) == (x.CompareTo(y) > 0)); #endif return(result); }
/// <summary> /// Merges two sorted lists of ranges and condenses the resulting one /// </summary> /// <param name="left">List of ranges to merge</param> /// <param name="right">List of ranges to merge</param> /// <returns>The sorted and condensed union of the two lists</returns> public static List <DateTimeRange> MergeFreeBusyLists( List <DateTimeRange> left, List <DateTimeRange> right) { IEnumerable <DateTimeRange> leftEnumerable = left as IEnumerable <DateTimeRange>; IEnumerator <DateTimeRange> leftEnumerator = leftEnumerable.GetEnumerator(); bool moreLeft = leftEnumerator.MoveNext(); IEnumerable <DateTimeRange> rightEnumerable = right as IEnumerable <DateTimeRange>; IEnumerator <DateTimeRange> rightEnumerator = rightEnumerable.GetEnumerator(); bool moreRight = rightEnumerator.MoveNext(); List <DateTimeRange> result = new List <DateTimeRange>(left.Capacity + right.Capacity); while (moreLeft && moreRight) { DateTimeRange leftRange = leftEnumerator.Current; DateTimeRange rightRange = rightEnumerator.Current; DateTimeRange range = null; if (leftRange.CompareTo(rightRange) < 0) { range = leftRange; moreLeft = leftEnumerator.MoveNext(); } else { range = rightRange; moreRight = rightEnumerator.MoveNext(); } result.Add(new DateTimeRange(range.Start, range.End)); } while (moreLeft) { DateTimeRange range = leftEnumerator.Current; result.Add(new DateTimeRange(range.Start, range.End)); moreLeft = leftEnumerator.MoveNext(); } while (moreRight) { DateTimeRange range = rightEnumerator.Current; result.Add(new DateTimeRange(range.Start, range.End)); moreRight = rightEnumerator.MoveNext(); } log.DebugFormat("Merged {0} + {1} into {2} ranges", left.Count, right.Count, result.Count); CondenseFreeBusyTimes(result); log.DebugFormat("Compressed {0} + {1} into {2} ranges", left.Count, right.Count, result.Count); return(result); }