【问题标题】:What is the most compact way using LINQ to check whether an IEnumerable<int> is ordered? [duplicate]使用 LINQ 检查 IEnumerable<int> 是否已排序的最紧凑方法是什么? [复制]
【发布时间】:2016-12-10 08:10:38
【问题描述】:

我想出了一个非常 LINQy 的方法

bool isOrdered = ids.Skip(1).Concat(new List<int>() { int.MaxValue })
       .Zip(ids, (y, x) => y >= x)
       .All(z => z);

但是,它不是非常高效或紧凑。有没有更好的办法?

【问题讨论】:

    标签: c# algorithm linq


    【解决方案1】:

    Aggregate 是一种遍历序列并跟踪先前项目的方法

    (new int[]{1,2,3}).Aggregate(
       new { IsSorted = true, Previous = int.MinValue },
       (state, current) => new {
           IsSorted = (state.IsSorted && current > state.Previous), 
           Previous = current})
     .IsSorted
    

    不幸的是,Aggregate 无法提前停止,这与 .Zip() 解决方案不同,您可以像示例中那样使用 .All 提前停止。

    【讨论】:

      【解决方案2】:
          var isOrdered = ids.Zip(ids.Skip(1), (curr, next) => curr <= next).All(x => x);
      

      【讨论】:

        【解决方案3】:

        如果您愿意受到更多限制并假设您拥有IList&lt;int&gt; 而不是IEnumerable&lt;int&gt;,您可以这样做,这样您就可以提前退出:

        ids.Skip(1).Select( (val,ix) => val >= ids.ElementAt(ix-1) ).All( x => x);
        

        它适用于任何可枚举但在 ids 不是 IList 的情况下它会是 O(n^2)。如果您需要它适用于任何 IEnumerable,那么@AlexeiLevenkov 的解决方案是最好的解决方案。

        【讨论】:

          猜你喜欢
          • 2010-12-01
          • 2016-09-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-16
          • 2016-09-29
          • 1970-01-01
          • 2012-04-02
          相关资源
          最近更新 更多