c# - 检查 List<Int32> 值是否连续

标签 c# linq list

List<Int32> dansConList = new List<Int32>();
dansConList[0] = 1;
dansConList[1] = 2;
dansConList[2] = 3;

List<Int32> dansRandomList = new List<Int32>();
dansRandomList[0] = 1;
dansRandomList[1] = 2;
dansRandomList[2] = 4;

我需要一个方法,在评估上述列表时,将返回 false对于 dansRandomListtrue对于 dansConList基于事实dansConList在它的值中有一个连续的数字序列,而 dansRandomList 没有(缺少值 3)。

如果可能,最好使用 LINQ。

我尝试过的:

  • 为了获得最终结果,我使用了一个 for 循环并与“i”(循环计数器)进行比较以评估值,但如上所述,我想为此使用 LINQ。

最佳答案

单行,只迭代到第一个非连续元素:

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

更新:举几个例子说明它是如何工作的:

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

* Select 不会产生第二个 4,Distinct 也不会检查它,因为 Any 会在找到前 4 个后停止。

关于c# - 检查 List<Int32> 值是否连续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13359327/

相关文章:

python - 在 Python 中按属性获取对象列表中的索引

r - 列表的行列表

python - 添加两个已经在同一个列表中的词典

c# - 获取 Azure 服务总线中的消息统计信息

c# - 委托(delegate) - 方法名称预期错误

c# - 正则表达式忽略方括号

C# Entity Framework .ToList() 但 CA1002 : Use Collection

linq - 优化 LINQ to SQL 查询

c# - C# 中 IEnumerable 类的 foreach 和 for 循环之间的区别

c# - 在单个查询中从多个表中选择记录计数