LINQ to find series of consecutive numbers

A linqish way can be writing an extension method GroupWhile like below (All checks omitted. not optimized to understand easily.)

int[] list = new int[] { 1, 2, 3, 5, 7, 8 };
var result = list.GroupWhile((x, y) => y - x == 1)
                 .Select(x => new {i = x.First(), len = x.Count()  })
                 .ToList();

public static IEnumerable<IEnumerable<T>> GroupWhile<T>(this IEnumerable<T> seq, Func<T,T,bool> condition)
{
    T prev = seq.First();
    List<T> list = new List<T>() { prev };

    foreach(T item in seq.Skip(1))
    {
        if(condition(prev,item)==false)
        {
            yield return list;
            list = new List<T>();
        }
        list.Add(item);
        prev = item;
    }

    yield return list;
}

TODO: use IGrouping 🙂

Leave a Comment