How to group ranges in LINQ

孤人 提交于 2019-12-03 21:46:12

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(),
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!