Check if List values are consecutive

前端 未结 12 1831
悲&欢浪女
悲&欢浪女 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:16

    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
    

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

提交回复
热议问题