using System.Collections.Generic;
public int Start { get; set;}
public int Stop { get; set;}
public static void Main()
var items = new Item[]{new Item{Start=1,Stop=2},new Item{Start=2,Stop=5},new Item{Start=8,Stop=10},new Item{Start=10,Stop=20}};
var seq = GetContiguousSequences3(items);
foreach(var seqItem in seq)
foreach(var item in seqItem)
Console.WriteLine(item.Start + " - " + item.Stop);
Console.WriteLine("--- end of group --");
public static List<Item[]> GetContiguousSequences2(Item []items)
return items.Select( (item,index) => new {
index = index == 0 || items[index-1].Stop == item.Start ? currIdx : ++currIdx
.GroupBy(x => x.index, x => x.item)
.Select(x => x.ToArray())
public static List<Item[]> GetContiguousSequences3(Item []items)
var res = items.Aggregate(new {Result = new List<Item[]>(), Curr = new List<Item>()}, (agg, item) => {
if(!agg.Curr.Any() || agg.Curr.Last().Stop == item.Start) {
agg.Result.Add(agg.Curr.ToArray());
res.Result.Add(res.Curr.ToArray());
public static List<Item[]> GetContiguousSequences(Item []items)
var ret = new List<Item[]>();
for(var i2=1;i2<items.Length;++i2)
if(items[i2-1].Stop != items[i2].Start)
ret.Add(items.Skip(i1).Take(num).ToArray());
ret.Add(items.Skip(i1).Take(items.Length-i1).ToArray());