检查List <int32>值是否连续</int32>

时间:2012-11-13 10:44:47

标签: 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的{​​{1}}为dansRandomListtrue返回dansConList它的值是连续的数字序列,而dansRandomList不是(缺少值3)。

如果可能,最好使用LINQ。

我尝试过的事情:

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

13 个答案:

答案 0 :(得分:45)

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

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

答案 1 :(得分:7)

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

答案 2 :(得分:7)

var result = list
    .Zip(list.Skip(1), (l, r) => l + 1 == r)
    .All(t => t);

答案 3 :(得分: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();
}

像这样使用:

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

答案 4 :(得分:2)

扩展方法:

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

用途:

bool isConsecutive = dansRandomList.IsConsecutive();

答案 5 :(得分: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

答案 6 :(得分:0)

这是一个使用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

答案 7 :(得分:0)

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

样品

isRepeatable(121878999, 2);

结果= True

因为9重复两次,其中最多没有连续的次数

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;

    }

答案 8 :(得分: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;

答案 9 :(得分: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;
}

答案 10 :(得分:-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();

答案 11 :(得分:-1)

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

var list = new int[] {-1,0,1,2,3};
var isConsecutive = list.Select((n,index) => n == index+list.ElementAt(0)).All (n => n);

答案 12 :(得分:-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;
}
相关问题