检查整数列表增加一个 [英] Check if a list of integers increments by one

查看:117
本文介绍了检查整数列表增加一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法,使用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.

这篇关于检查整数列表增加一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆