c# - native C# 支持检查 IEnumerable 是否已排序?

标签 c# linq sorting sortedlist icomparable

是否有任何 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;
}

还有一个使用 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;
}

最佳答案

您可以检查集合是否为 IOrderedEnumerable但这只有在排序是应用于序列的最后一个操作时才有效。所以,基本上你需要手动检查所有序列。

还要记住,如果序列是 IOrderedEnumerable你真的不能说哪个条件用于排序序列。


这是一个通用方法,您可以使用它来检查序列是否按您要检查的字段按升序排序:

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;
}

用法:

string[] source = { "a", "ab", "c" };
bool isOrdered = source.IsOrdered(s => s.Length);

您可以创建类似的 IsOrderedDescending方法 - 只需将检查比较结果更改为 comparer.Compare(current, next) < 0 .

关于c# - native C# 支持检查 IEnumerable 是否已排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19786101/

相关文章:

c - QSort 在 cmp 函数中返回错误(乱序?)的数字

c# - 确定数据库是否是 Azure 数据库

c# - LINQ 按文本搜索

c# - 使用 LINQ 处理文本文件

c# - 在LINQ查询中动态设置表名

c# - 将字符串拆分为数组并对数组进行排序

Java根据关键字排序

C排序改变数组中的值

c# - 通过 lambdas 构造 where 的表达式

c# - Intellisense 不适用于 VS2010 中的一个特定项目