문제

Here is the data that I would like to group.

Start      End
  2         4
  26        30
  5         9
  20        24
  18        19

Because I have 18 - 19 and 20 - 24. I would add these two together as 18 - 24. In this case the rule is (a, b) => b.start - a.end = 1 and the result would be

Start      End
  18        24
  2         9
  26        30

EDIT added last result row per comments below.

도움이 되었습니까?

해결책

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(),
    });
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top