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

前端 未结 8 2900
旧巷少年郎
旧巷少年郎 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 17:55

    Here is a one-liner that will work:

    var isIncreasing = list.OrderBy(x => x).SequenceEqual(list);
    

    Or if you're going for performance, here is a one-liner that will only traverse the list once, and quits as soon as it reaches an element out of sequence:

    var isIncreasing = !list.SkipWhile((x, i) => i == 0 || list[i - 1] <= x).Any();
    

提交回复
热议问题