I have this Extension method to check if a List of any type is sorted
public static bool IsSorted<T>(this IEnumerable<T> input)
{
IEnumerable<T> expectedListASC = input.OrderBy(x => x);
IEnumerable<T> expectedListDESC = input.OrderByDescending(x => x);
return expectedListASC.SequenceEqual(input) || expectedListDESC.SequenceEqual(input);
}
But with large Lists it takes time. Is there a more efficient way to get the same result?
Here's a generic method that ought to detect whether the sequence is in increasing or decreasing order, and then checking if the rest of the collection follows suit.
It has not been fully tested, you should throw datasets to it left and right and write unit-tests if you decide to use this.
public static class CollectionExtensions
{
public static bool IsOrdered<T>(this IEnumerable<T> collection, IComparer<T> comparer = null)
{
comparer = comparer ?? Comparer<T>.Default;
bool? expectedToIncrease = null;
using (var enumerator = collection.GetEnumerator())
{
bool gotFirst = enumerator.MoveNext();
if (!gotFirst)
return true; // empty collection is ordered
var first = enumerator.Current;
T second = default(T);
while (expectedToIncrease is null)
{
bool gotSecond = enumerator.MoveNext();
if (!gotSecond)
return true; // only equal elements are ordered
second = enumerator.Current;
switch (comparer.Compare(first, second))
{
case int i when i < 0:
expectedToIncrease = false;
break;
case int i when i > 0:
expectedToIncrease = true;
break;
}
if (expectedToIncrease is null)
first = second; // prepare for next round
}
while (enumerator.MoveNext())
{
if (expectedToIncrease.GetValueOrDefault())
{
if (comparer.Compare(second, enumerator.Current) < 0)
return false;
}
else
{
if (comparer.Compare(second, enumerator.Current) > 0)
return false;
}
}
return true;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With