Check if List<Int32> values are consecutive

One-liner, only iterates until the first non-consecutive element:

bool isConsecutive = !myIntList.Select((i,j) => i-j).Distinct().Skip(1).Any();

Update: a couple examples of how this works:

Input is { 5, 6, 7, 8 }
Select yields { (5-0=)5, (6-1=)5, (7-2=)5, (8-3=)5 }
Distinct yields { 5, (5 not distinct, 5 not distinct, 5 not distinct) }
Skip yields { (5 skipped, nothing left) }
Any returns false
Input is { 1, 2, 6, 7 }
Select yields { (1-0=)1, (2-1=)1, (6-2=)4, (7-3=)4 } *
Distinct yields { 1, (1 not distinct,) 4, (4 not distinct) } *
Skip yields { (1 skipped,) 4 }
Any returns true

* The Select will not yield the second 4 and the Distinct will not check it, as the Any will stop after finding the first 4.


var min = list.Min();
var max = list.Max();
var all = Enumerable.Range(min, max - min + 1);
return list.SequenceEqual(all);

var result = list
    .Zip(list.Skip(1), (l, r) => l + 1 == r)
    .All(t => t);

Tags:

C#

Linq

List