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

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

    public static class EnumerableExtensions
    {
        private static bool CompareAdjacentElements(this IEnumerable source,
            Func comparison)
        {
            using (var iterator = source.GetEnumerator())
            {
                if (!iterator.MoveNext())
                    throw new ArgumentException("The input sequence is empty", "source");
                var previous = iterator.Current;
                while (iterator.MoveNext())
                {
                    var next = iterator.Current;
                    if (comparison(previous, next)) return false;
                    previous = next;
                }
                return true;
            }
        }
    
        public static bool IsSorted(this IEnumerable source)
            where TSource : IComparable
        {
            return CompareAdjacentElements(source, (previous, next) => previous.CompareTo(next) > 0);
        }
    
        public static bool IsSorted(this IEnumerable source, Comparison comparison)
        {
            return CompareAdjacentElements(source, (previous, next) => comparison(previous, next) > 0);
        }
    
        public static bool IsStrictSorted(this IEnumerable source)
            where TSource : IComparable
        {
            return CompareAdjacentElements(source, (previous, next) => previous.CompareTo(next) >= 0);
        }
    
        public static bool IsStrictSorted(this IEnumerable source, Comparison comparison)
        {
            return CompareAdjacentElements(source, (previous, next) => comparison(previous, next) >= 0);
        }
    }
    

提交回复
热议问题