You can check if the collection is IOrderedEnumerable , but this will only work if the ordering is the last operation that was applied to the sequence. So basically you need to check the whole sequence manually.
Also keep in mind that if a sequence is IOrderedEnumerable , you really cannot tell which condition was used to sort the sequence.
Here is a general method that you can use to check if a sequence is sorted in ascending order by the field you want to check:
public static bool IsOrdered<T, TKey>( this IEnumerable<T> source, Func<T, TKey> keySelector) { if (source == null) throw new ArgumentNullException("source"); var comparer = Comparer<TKey>.Default; using (var iterator = source.GetEnumerator()) { if (!iterator.MoveNext()) return true; TKey current = keySelector(iterator.Current); while (iterator.MoveNext()) { TKey next = keySelector(iterator.Current); if (comparer.Compare(current, next) > 0) return false; current = next; } } return true; }
Using:
string[] source = { "a", "ab", "c" }; bool isOrdered = source.IsOrdered(s => s.Length);
You can create a similar IsOrderedDescending method - just change the result of the comparison check to comparer.Compare(current, next) < 0 .
source share