C# 使用LINQ检查IEnumerable<;int>;订了什么?
我想出了一个非常关键的方法C# 使用LINQ检查IEnumerable<;int>;订了什么?,c#,algorithm,linq,C#,Algorithm,Linq,我想出了一个非常关键的方法 bool isOrdered = ids.Skip(1).Concat(new List<int>() { int.MaxValue }) .Zip(ids, (y, x) => y >= x) .All(z => z); bool isOrdered=ids.Skip(1).Concat(新列表(){int.MaxValue}) .Zip(ID,(y,x)=>y>=x) .全部(z=>z); 但是,它不是
bool isOrdered = ids.Skip(1).Concat(new List<int>() { int.MaxValue })
.Zip(ids, (y, x) => y >= x)
.All(z => z);
bool isOrdered=ids.Skip(1).Concat(新列表(){int.MaxValue})
.Zip(ID,(y,x)=>y>=x)
.全部(z=>z);
但是,它不是非常高效或紧凑。有更好的办法吗
Aggregate
是一种按顺序浏览并跟踪以前项目的方法
不幸的是,
Aggregate
没有办法提前停止,这与.Zip()
解决方案不同,在该解决方案中,您可以使用样本中的.All
提前停止。Aggregate
是一种按顺序行走并跟踪以前项目的方法
var isOrdered = ids.Zip(ids.Skip(1), (curr, next) => curr <= next).All(x => x);
不幸的是,Aggregate
没有办法提前停止,这与.Zip()解决方案不同,在该解决方案中,您可以使用示例中的.All
提前停止。var isOrdered=ids.Zip(ids.Skip(1),(curr,next)=>curr x);
var isOrdered = ids.Zip(ids.Skip(1), (curr, next) => curr <= next).All(x => x);
var isOrdered=ids.Zip(ids.Skip(1),(curr,next)=>curr x);
如果您愿意稍微约束一点,并假设您有一个IList
而不是IEnumerable
,您可以这样做,这允许您提前退出:
ids.Skip(1).Select( (val,ix) => val >= ids.ElementAt(ix-1) ).All( x => x);
它将用于任何可枚举项,但在ids不是IList的情况下,它将是O(n^2)。如果你需要它来为任何IEnumerable工作,那么@AlexeiLevenkov的解决方案是最好的。如果你愿意稍微约束一点,并假设你有一个IList
而不是IEnumerable,你可以这样做,这允许你提前退出:
ids.Skip(1).Select( (val,ix) => val >= ids.ElementAt(ix-1) ).All( x => x);
它将用于任何可枚举项,但在ids不是IList的情况下,它将是O(n^2)。如果你需要这个来处理任何IEnumerable,那么@AlexeiLevenkov的解决方案是最好的