Another option is to use Aggregate to repeat a sequence only once.
Note that unlike All suggested by Reed Copsi, Aggregate cannot stop in the middle when the condition fails ...
var s = new int[] {3,4,5,6}.ToList(); var isSequential = s.Aggregate ( new {PrevValue = 0, isFirst = true, Success = true} , (acc, current) => new { PrevValue = current, isFirst = false, Success = acc.Success && (acc.isFirst || (acc.PrevValue == current - 1)) } ) .Success;
The Fancier version should be to have an iterator that wraps the previous value along or special code that will split the iterator into "First and the rest", allowing you to implement a Reed solution with a single iteration for any enumerated.
Alexei Levenkov
source share