是否有任何LINQ支持检查是否IEnumerable<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;
}
Run Code Online (Sandbox Code Playgroud)
一个使用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 …Run Code Online (Sandbox Code Playgroud)