有没有一种方法,使用LINQ,以检查是否整数列表是连续 - 即1,2,3,4,5或14,15,16,17,18
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?
推荐答案您可以做到这一点通过 Enumerable.Zip :
You could do this via Enumerable.Zip:
bool sequential = values.Zip(values.Skip(1), (a,b) => (a+1) == b).All(x => x);此工作通过取每对的值,并检查是否所述第二比1更第一,并返回布尔值。如果所有对符合标准的值是连续的。
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);这将只可通过索引访问序列工作。注意,我们使用值[I] ,而不是值[I-1] ,因为跳过呼叫转移有效的索引。
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.