Check if List<Int32> values are consecutive

Check if List<Int32> values are consecutive

One-liner, only iterates until the first non-consecutive element:

bool isConsecutive = !myIntList.Select((i,j) => i-j).Distinct().Skip(1).Any();

Update: a couple examples of how this works:

Input is { 5, 6, 7, 8 }
Select yields { (5-0=)5, (6-1=)5, (7-2=)5, (8-3=)5 }
Distinct yields { 5, (5 not distinct, 5 not distinct, 5 not distinct) }
Skip yields { (5 skipped, nothing left) }
Any returns false
Input is { 1, 2, 6, 7 }
Select yields { (1-0=)1, (2-1=)1, (6-2=)4, (7-3=)4 } *
Distinct yields { 1, (1 not distinct,) 4, (4 not distinct) } *
Skip yields { (1 skipped,) 4 }
Any returns true

* The Select will not yield the second 4 and the Distinct will not check it, as the Any will stop after finding the first 4.

 

 

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(159)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2016-10-21 Group By
2016-10-21 The property 'RowId' is part of the object's key information and cannot be modified.
2016-10-21 HashCheck
2016-10-21 File Checksum Integrity Verifier
2015-10-21 Weak Event Patterns
2015-10-21 C#中的多文档的使用
2015-10-21 如何将一个Form中的代码拆分到多个文件中
点击右上角即可分享
微信分享提示