I\'m interested if there is a way, in LINQ, to check if all numbers in a list are increasing monotonically?
Example
List l
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);
}
}