21
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;

我需要一种方法,在评估上述列表时,将根据事实返回falsefordansRandomListtruefor在它的值中有一个连续的数字序列,而 dansRandomList 没有(缺少值 3)。dansConListdansConList

如果可能,最好使用 LINQ。

我试过的:

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

13 回答 13

63

单线,仅迭代直到第一个非连续元素:

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 后停止。

于 2012-11-13T11:07:39.720 回答
10
var min = list.Min();
var max = list.Max();
var all = Enumerable.Range(min, max - min + 1);
return list.SequenceEqual(all);
于 2012-11-13T10:50:44.143 回答
9
var result = list
    .Zip(list.Skip(1), (l, r) => l + 1 == r)
    .All(t => t);
于 2012-11-13T11:07:17.927 回答
6

您可以使用此扩展方法:

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();
}

像这样使用它:

[Test]
public void ConsecutiveTest()
{
    var ints = new List<int> {1, 2, 4};
    bool isConsecutive = ints.IsConsecutive();
}
于 2012-11-13T10:52:43.730 回答
3

扩展方法:

public static bool IsConsecutive(this IEnumerable<int> myList)
{
    return myList.SequenceEqual(Enumerable.Range(myList.First(), myList.Last()));
}

用途:

bool isConsecutive = dansRandomList.IsConsecutive();
于 2012-11-13T10:51:09.377 回答
0

这是另一个。它同时支持 {1,2,3,4} 和 {4,3,2,1}。它测试序号差异等于 1 或 -1。

Function IsConsecutive(ints As IEnumerable(Of Integer)) As Boolean
    If ints.Count > 1 Then
        Return Enumerable.Range(0, ints.Count - 1).
            All(Function(r) ints(r) + 1 = ints(r + 1) OrElse ints(r) - 1 = ints(r + 1))
    End If

    Return False
End Function
于 2012-12-08T10:18:14.783 回答
0

警告:如果为空,则返回 true。

var list = new int[] {-1,0,1,2,3};
var isConsecutive = list.Select((n,index) => n == index+list.ElementAt(0)).All (n => n);
于 2017-02-10T20:26:25.743 回答
0

为了检查系列是否包含连续数字,您可以使用它

样本

isRepeatable(121878999, 2);

结果 = 真

因为 9 重复了两次,其中 upto 不是连续的次数

isRepeatable(37302293, 3)

结果 = 假

因为没有数字连续重复3次

static bool isRepeatable(int num1 ,int upto)
    {
        List<int> myNo = new List<int>();
        int previous =0;
        int series = 0;
        bool doesMatch = false;
        var intList = num1.ToString().Select(x => Convert.ToInt32(x.ToString())).ToList();
        for (int i = 0; i < intList.Count; i++)
        {
            if (myNo.Count==0)
            {
                myNo.Add(intList[i]);
                previous = intList[i];
                series += 1;
            }
            else
            {
                if (intList[i]==previous)
                {
                    series += 1;
                    if (series==upto)
                    {
                        doesMatch = true;
                        break;
                    }
                }
                else
                {
                    myNo = new List<int>();
                    previous = 0;
                    series = 0;
                }
            }
           
        }

        return doesMatch;

    }
于 2020-08-26T08:57:40.230 回答
0
// 1 | 2 | 3 | 4 | _
// _ | 1 | 2 | 3 | 4
//   | 1 | 1 | 1 |    => must be 1 (or 2 for even/odd consecutive integers)

var numbers = new List<int>() { 1, 2, 3, 4, 5 };
const step = 1; // change to 2 for even and odd consecutive integers

var isConsecutive = numbers.Skip(1)
   .Zip(numbers.SkipLast(1))
   .Select(n => {
       var diff = n.First - n.Second;
       return (IsValid: diff == step, diff);
   })
   .Where(diff => diff.IsValid)
   .Distinct()
   .Count() == 1;

或者我们可以写得更短一些但可读性较差:

var isConsecutive = numbers.Skip(1)
   .Zip(numbers.SkipLast(1), (l, r) => (IsValid: (l-r == step), l-r))
   .Where(diff => diff.IsValid)
   .Distinct()
   .Count() == 1;
于 2020-09-03T23:03:03.170 回答
0

老问题,但这是使用一些简单代数的简单方法。

这仅在您的整数从 1 开始时才有效。

public bool AreIntegersConsecutive(List<int> integers)
{
    var sum = integers.Sum();
    var count = integers.Count();
    var expectedSum = (count * (count + 1)) / 2;

    return expectedSum == sum;
}
于 2021-04-21T17:31:48.537 回答
-1

它仅适用于唯一列表。

List<Int32> dansConList = new List<Int32>();
dansConList.Add(7);
dansConList.Add(8);
dansConList.Add(9);

bool b = (dansConList.Min() + dansConList.Max())*((decimal)dansConList.Count())/2.0m == dansConList.Sum();
于 2012-11-13T10:59:20.037 回答
-1

这是一个使用该Aggregate函数的扩展方法。

public static bool IsConsecutive(this List<Int32> value){
    return value.OrderByDescending(c => c)
                .Select(c => c.ToString())
                .Aggregate((current, item) => 
                            (item.ToInt() - current.ToInt() == -1) ? item : ""
                            )
                .Any();
}

用法:

var consecutive = new List<Int32>(){1,2,3,4}.IsConsecutive(); //true
var unorderedConsecutive = new List<Int32>(){1,4,3,2}.IsConsecutive(); //true
var notConsecutive = new List<Int32>(){1,5,3,4}.IsConsecutive(); //false
于 2017-03-08T10:15:19.630 回答
-2

这是一个C版本的代码,我认为根据逻辑用其他语言重写它很容易。

int isConsecutive(int *array, int length) {
     int i = 1;
     for (; i < length; i++) {
          if (array[i] != array[i - 1] + 1)
              return 0; //which means false and it's not a consecutive list
     }

     return 1;
}
于 2012-11-13T10:52:35.947 回答