Wilson - 9 months ago 63

C# Question

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

Answer

You could 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 to see if the second is 1 more than the first, and returning booleans. If all pairs fit the criteria, the values are sequential.

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

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

This will only work on sequences which can be accessed by index. Note that we use `values[i]`

, not `values[i-1]`

, as the `Skip`

call effectively shifts the indices.

Source (Stackoverflow)