How to group ranges in LINQ

坚强是说给别人听的谎言 提交于 2019-12-21 06:26:55

问题


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.


回答1:


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(),
    });


来源:https://stackoverflow.com/questions/22255438/how-to-group-ranges-in-linq

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