Check if the number of integers increases by one

Is there a way with LINQ to check if the list of integers is "sequential" - i.e. 1,2,3,4,5 or 14,15,16,17,18?

+7
source share
4 answers

You can do this via Enumerable.Zip :

bool sequential = values.Zip(values.Skip(1), (a,b) => (a+1) == b).All(x => x); 

This works by taking each pair of values ​​and checking if the second is 1 more than the first and returns boolean values. If all pairs meet the criteria, the values ​​are consecutive.


Given that this is a list of integers, you can do this somewhat more efficiently using:

 bool sequential = values.Skip(1).Select((v,i) => v == (values[i]+1)).All(v => v); 

This will only work with sequences that can be accessed by index. Note that we are using values[i] , not values[i-1] , since calling Skip effectively changes indexes.

+16
source
 bool isSequential = Enumerable.Range(values.Min(), values.Count()) .SequenceEqual(values); 
+11
source

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.

+2
source

If you already know that the numbers that you have in the list are unique as well as sorted , then the simplest check for sequential is simply

 lst[lst.Count - 1] - lst[0] == lst.Count - 1 

Assume at least one item in a list.

-one
source

All Articles