As a follow up to the method that collapses overlapping ranges I thought I would try to create a method that combines adjacent ranges.
Basically, after running the Collapse method you may end up with for example 1 to 5 and 6 to 10. I would like to combine those into one range, 1 to 10.
This is what I have come up with so far, but it doesn't really work very well. Does anyone spot my problem or have good alternative solution?
public static IEnumerable<Range<T>> MergeAdjacent<T>(this IEnumerable<Range<T>> source, Func<T, T, bool> isAdjacent)
{
using (var sourceIterator = source.GetEnumerator())
{
if (!sourceIterator.MoveNext())
yield break;
var first = sourceIterator.Current;
while (sourceIterator.MoveNext())
{
var second = sourceIterator.Current;
if (isAdjacent(first.End, second.Start))
{
yield return Range.Create(first.Start, second.End);
}
else
yield return first;
first = second;
}
yield return first;
}
}