Here is a solution that uses the Segment
operator from the MoreLinq library.
using System;
using System.Linq;
using static MoreLinq.Extensions.SegmentExtension;
public class Program
{
public static void Main()
{
int[] source = new[] { 1, 2, 3, 5, 6, 8, 9, 10 };
int[][] result = source
.Segment((current, previous, _) => current != previous + 1)
.Select(segment => segment.ToArray())
.ToArray();
Console.Write($"[{String.Join(", ", source)}]");
Console.Write($" => ");
Console.WriteLine($@"[{String.Join(", ", result
.Select(s => $"[{String.Join(", ", s)}]"))}]");
}
}
Output:
[1, 2, 3, 5, 6, 8, 9, 10] => [[1, 2, 3], [5, 6], [8, 9, 10]]
Try it on fiddle.
The Segment
extension method has the signature below:
public static IEnumerable<IEnumerable<T>> Segment<T>(
this IEnumerable<T> source,
Func<T, T, int, bool> newSegmentPredicate);