Is it possible to use LINQ to check if all numbers in a list are increasing monotonically?

前端 未结 8 2844
旧巷少年郎
旧巷少年郎 2021-02-20 17:14

I\'m interested if there is a way, in LINQ, to check if all numbers in a list are increasing monotonically?

Example

List l         


        
8条回答
  •  佛祖请我去吃肉
    2021-02-20 18:12

    public static bool IsIncreasingMontonically(List list) 
        where T : IComparable
    {
        return list.Zip(list.Skip(1), (a, b) => a.CompareTo(b) <= 0)
            .All(b => b);
    }
    

    Note that this iterates the sequence twice. For a List, that's not a problem at all, for an IEnumerable or IQueryable, that could be bad, so be careful before you just change List to IEnumerable.

提交回复
热议问题