是否有任何 LINQ 支持检查 anIEnumerable<T>是否已排序?我有一个我想验证的枚举是否按非降序排序,但我似乎无法在 C# 中找到对它的本机支持。
我已经使用以下方法编写了自己的扩展方法IComparables<T>:
public static bool IsSorted<T>(this IEnumerable<T> collection) where T : IComparable<T>
{
   Contract.Requires(collection != null);
   using (var enumerator = collection.GetEnumerator())
   {
      if (enumerator.MoveNext())
      {
         var previous = enumerator.Current;
         while (enumerator.MoveNext())
         {
            var current = enumerator.Current;
            if (previous.CompareTo(current) > 0)
               return false;
            previous = current;
         }
      }
   }
   return true;
}
还有一个使用IComparer<T>对象:    
public static bool IsSorted<T>(this IEnumerable<T> collection, IComparer<T> comparer)
{
   Contract.Requires(collection != null);
   using (var enumerator = collection.GetEnumerator())
   {
      if (enumerator.MoveNext())
      {
          var previous = enumerator.Current;
         while (enumerator.MoveNext())
         {
            var current = enumerator.Current;
            if (comparer.Compare(previous, current) > 0)
                return false;
            previous = current;
         }
      }
   }
   return true;
}