Check if List values are consecutive

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

    You can use this extension method:

    public static bool IsConsecutive(this IEnumerable 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();
    }
    

    Use it like this:

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

提交回复
热议问题