So we'll start with a helper method called GroupWhile
. It will be provided with a predicate accepting two items from the sequence, the previous and the current. If that predicate returns true, the current item goes into the same group as the previous item. If not, it starts a new group.
public static IEnumerable<IEnumerable<T>> GroupWhile<T>(
this IEnumerable<T> source, Func<T, T, bool> predicate)
{
using (var iterator = source.GetEnumerator())
{
if (!iterator.MoveNext())
yield break;
List<T> list = new List<T>() { iterator.Current };
T previous = iterator.Current;
while (iterator.MoveNext())
{
if (!predicate(previous, iterator.Current))
{
yield return list;
list = new List<T>();
}
list.Add(iterator.Current);
previous = iterator.Current;
}
yield return list;
}
}
Once we have this we can order the items by the start, then by the end date, group them while the previous range's end overlaps with the next range's start, and then collapse each group into a new range based on the groups start and end values.
var collapsedRanges = ranges.OrderBy(range => range.Start)
.ThenBy(range => range.End)
.GroupWhile((prev, cur) => prev.End + 1 >= cur.Start)
.Select(group => new Range()
{
Start = group.First().Start,
End = group.Select(range => range.End).Max(),
});