检查List <Int32>值是否连续

16 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;
Run Code Online (Sandbox Code Playgroud)

我需要一种方法,在评估上面的列表时,将返回falsefor dansRandomListtruefor,dansConList基于事实dansConList在其值中有一个连续的数字序列,而dansRandomList则没有(缺少值3).

如果可能,最好使用LINQ.

我试过的:

  • 为了达到最终结果,我使用了for循环并与'i'(循环计数器)进行比较以评估值,但如上所述,我想使用LINQ.

Raw*_*ing 48

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

bool isConsecutive = !myIntList.Select((i,j) => i-j).Distinct().Skip(1).Any();
Run Code Online (Sandbox Code Playgroud)

更新:有关其工作原理的几个示例:

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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)

*Select不会产生第二个4而Distinct不会检查它,因为Any会在找到第一个4之后停止.

  • +1创造性地使用linq,可能以牺牲可读性为代价:) (7认同)
  • @ChrisNevill这是[这个](https://msdn.microsoft.com/en-us/library/bb534869.aspx)重载`Select`(*通过合并元素的索引*将序列的每个元素投影到一个新的形式中*).注意参数是`Func <TSource,Int32,TResult>` - 获取源项和整数并返回结果项. (2认同)

Kie*_*one 8

var min = list.Min();
var max = list.Max();
var all = Enumerable.Range(min, max - min + 1);
return list.SequenceEqual(all);
Run Code Online (Sandbox Code Playgroud)

  • 我的问题是它列举了原始列表3次,一次是min,一次是max,一次是比较. (3认同)
  • @Kieren Johnstone应该是Enumerable.Range(min,max-min) (2认同)
  • 不正确,`Range`的第二个参数是`count` (2认同)

Cam*_*and 7

var result = list
    .Zip(list.Skip(1), (l, r) => l + 1 == r)
    .All(t => t);
Run Code Online (Sandbox Code Playgroud)


Joh*_*son 5

您可以使用此扩展方法:

public static bool IsConsecutive(this IEnumerable<int> ints )
{
    //if (!ints.Any())
    //    return true; //Is empty consecutive?
    // I think I prefer exception for empty list but I guess it depends
    int start = ints.First();
    return !ints.Where((x, i) => x != i+start).Any();
}
Run Code Online (Sandbox Code Playgroud)

像这样使用它:

[Test]
public void ConsecutiveTest()
{
    var ints = new List<int> {1, 2, 4};
    bool isConsecutive = ints.IsConsecutive();
}
Run Code Online (Sandbox Code Playgroud)