检查列表<&的Int32 GT;值是连续 [英] Check if List<Int32> values are consecutive

查看:103
本文介绍了检查列表<&的Int32 GT;值是连续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;

我需要一个方法,评估上述列表时,将返回 dansRandomList 真正基于这样的事实 dansConList dansConList 在一个连续的数字序列它的价值观,dansRandomList没有(缺值3)。

I need a method that, when evaluating the above lists, will return false for dansRandomList and true for dansConList based on the fact dansConList has a consecutive number sequence in it's values, and dansRandomList does not (missing the value 3).

使用LINQ是preferable,如果可能的话。

Using LINQ is preferable, if possible.

我已经试过:


  • 为了实现最终结果的缘故,我使用了一个for循环,并与I(循环计数器)比较,以评估值,但如上所述,我想使用LINQ这一点。

推荐答案

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

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

*的选择不会产生第二个4和鲜明不会检查它,因为任何在发现前4后停止。

* 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.

这篇关于检查列表&LT;&的Int32 GT;值是连续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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