Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用LINQ检查IEnumerable<;int>;订了什么?_C#_Algorithm_Linq - Fatal编程技术网

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的解决方案是最好的