【发布时间】: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);
但是,它不是非常高效或紧凑。有没有更好的办法?
【问题讨论】:
我想出了一个非常 LINQy 的方法
bool isOrdered = ids.Skip(1).Concat(new List<int>() { int.MaxValue })
.Zip(ids, (y, x) => y >= x)
.All(z => z);
但是,它不是非常高效或紧凑。有没有更好的办法?
【问题讨论】:
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 提前停止。
【讨论】:
var isOrdered = ids.Zip(ids.Skip(1), (curr, next) => curr <= next).All(x => x);
【讨论】:
如果您愿意受到更多限制并假设您拥有IList<int> 而不是IEnumerable<int>,您可以这样做,这样您就可以提前退出:
ids.Skip(1).Select( (val,ix) => val >= ids.ElementAt(ix-1) ).All( x => x);
它适用于任何可枚举但在 ids 不是 IList 的情况下它会是 O(n^2)。如果您需要它适用于任何 IEnumerable,那么@AlexeiLevenkov 的解决方案是最好的解决方案。
【讨论】: