Suppose I have the following array (my sequences are sorted in ascending order and contain positive integers)
var mySequence = new [] {1, 2, 3, 7, 8, 9, 15, 16, 17};
I want to write a linq query to select continuous numbers in a series viewed as a group. So, in the above example, I would get {[1, 2, 3], [7, 8, 9], [15, 16, 17]}.
I could write a sequence of foreach() , pass through each element and see where the sequence takes the jump and get the group there. But is there any LINQ method? I could move my foreach() code to a new extension method, so my code still looks LINQy, but I'm wondering if there is anything in System.Linq for this.
EDIT: I created my own extension (as follows), but Me.Name came up with something very smart in my answer.
internal class Sequence { public int Start { get; set; } public int End { get; set; } } internal static class EnumerableMixins { public static IEnumerable<Sequence> GroupFragments(this IEnumerable<int> sequence) { if (sequence.Any()) { var lastNumber = sequence.First(); var firstNumber = lastNumber; foreach(var number in sequence.Skip(1)) { if (Math.Abs(number - lastNumber) > 1) { yield return new Sequence() { Start = firstNumber, End = lastNumber }; firstNumber = lastNumber = number; } else { lastNumber = number; } } yield return new Sequence() { Start = firstNumber, End = lastNumber }; } } }
source share