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

前端 未结 8 2881
旧巷少年郎
旧巷少年郎 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

    Use a loop! It's short, fast and readable. With the exception of Servy's answer, most the solutions in this thread are unnecessarily slow (sorting takes 'n log n' time) .

    // Test whether a sequence is strictly increasing.
    public bool IsIncreasing(IEnumerable list)
    {
        bool initial = true;
        double last = Double.MinValue;
        foreach(var x in list)
        {
            if (!initial && x <= last)
                return false;
    
            initial = false;
            last = x;
        }
    
        return true;
    }
    

    Examples

    1. IsIncreasing(new List{1,2,3}) returns True
    2. IsIncreasing(new List{1,3,2}) returns False

提交回复
热议问题