Check if List values are consecutive

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

    Here is an extension method that uses the Aggregate function.

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

    Usage:

    var consecutive = new List(){1,2,3,4}.IsConsecutive(); //true
    var unorderedConsecutive = new List(){1,4,3,2}.IsConsecutive(); //true
    var notConsecutive = new List(){1,5,3,4}.IsConsecutive(); //false
    

提交回复
热议问题