The following algorithm in C # does what you want. It uses DateTime interval intervals, but you can adjust it as you like. As soon as the collection is sorted in ascending order of the beginning, if the beginning of the next interval is at or to the end of the previous, they overlap, and you increase the end time, if necessary. Otherwise, they do not overlap, and you save the previous result.
public static List<DateTimeRange> MergeTimeRanges(List<DateTimeRange> inputRanges) { List<DateTimeRange> mergedRanges = new List<DateTimeRange>(); // Sort in ascending start order. inputRanges.Sort(); DateTime currentStart = inputRanges[0].Start; DateTime currentEnd = inputRanges[0].End; for (int i = 1; i < inputRanges.Count; i++) { if (inputRanges[i].Start <= currentEnd) { if (inputRanges[i].End > currentEnd) { currentEnd = inputRanges[i].End; // Extend range. } } else { // Save current range to output. mergedRanges.Add(new DateTimeRange(currentStart, currentEnd)); currentStart = inputRanges[i].Start; currentEnd = inputRanges[i].End; } } mergedRanges.Add(new DateTimeRange(currentStart, currentEnd)); return mergedRanges; }
source share