You can check if collection is IOrderedEnumerable
but that will work only if ordering is the last operation which was applied to sequence. So, basically you need to check all sequence manually.
Also keep in mind, that if sequence is IOrderedEnumerable
you really can't say which condition was used to sort sequence.
Here is generic method which you can use to check if sequence is sorted in ascending order by 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;
}
Usage:
string[] source = { "a", "ab", "c" };
bool isOrdered = source.IsOrdered(s => s.Length);
You can create similar IsOrderedDescending
method - just change checking comparison result to comparer.Compare(current, next) < 0
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…