Check if List values are consecutive

前端 未结 12 1819
悲&欢浪女
悲&欢浪女 2021-02-01 05:46
List dansConList = new List();
dansConList[0] = 1;
dansConList[1] = 2;
dansConList[2] = 3;

List dansRandomList = new List

        
12条回答
  •  清歌不尽
    2021-02-01 06:38

    // 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() { 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;
    

    Or we could write that a bit shorter but less readable:

    var isConsecutive = numbers.Skip(1)
       .Zip(numbers.SkipLast(1), (l, r) => (IsValid: (l-r == step), l-r))
       .Where(diff => diff.IsValid)
       .Distinct()
       .Count() == 1;
    

提交回复
热议问题