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

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

    If you want to check whether a list always is increasing from index to index:

    IEnumerable<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 10 };
    bool allIncreasing = !list
        .Where((i, index) => index > 0 && list.ElementAt(index - 1) >= i)
        .Any();
    

    Demo

    But in my opinion a simple loop would be more readable in this case.

    0 讨论(0)
  • 2021-02-20 18:20

    Consider an implementation like the following, which enumerates the given IEnumerable only once. Enumerating can have side-effects, and callers typically expect a single pass-through if that's possible.

    public static bool IsIncreasingMonotonically<T>(
        this IEnumerable<T> _this)
        where T : IComparable<T>
    {
        using (var e = _this.GetEnumerator())
        {
            if (!e.MoveNext())
                return true;
            T prev = e.Current;
            while (e.MoveNext())
            {
                if (prev.CompareTo(e.Current) > 0)
                    return false;
                prev = e.Current;
            }
            return true;
        }
    }
    
    0 讨论(0)
提交回复
热议问题