C# - Aggregate( ) 中的终止
从下面的模拟中,
int[] amountWithdrawal = { 10, 20, 30, 140, 50, 70 };
amountWithdrawal.Aggregate(100, (balance, withdrawal) =>
{
Console.WriteLine("balance :{0},Withdrawal:{1}", balance, withdrawal);
if (balance >= withdrawal)
{
return balance - withdrawal;
}
else return balance;
}
);
我想在余额小于提款时终止聚合。但是我的代码遍历了整个数组。如何终止它?
From the following simulation
int[] amountWithdrawal = { 10, 20, 30, 140, 50, 70 };
amountWithdrawal.Aggregate(100, (balance, withdrawal) =>
{
Console.WriteLine("balance :{0},Withdrawal:{1}", balance, withdrawal);
if (balance >= withdrawal)
{
return balance - withdrawal;
}
else return balance;
}
);
I want to terminate the Aggregation when the balance is less than the withdrawal
.But my code travels the entire array.How to terminate it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在我看来,您需要一个 Accumulate 方法来生成新的累积值序列,而不是标量。像这样的东西:
然后你可以应用
TakeWhile
:我可以发誓在正常的 LINQ to Objects 中存在类似的东西,但我现在找不到它......
It seems to me that you want an
Accumulate
method which yields a new sequence of accumulated values, instead of a scalar. Something like this:Then you could apply
TakeWhile
:I could have sworn there was something like this in normal LINQ to Objects, but I can't find it at the moment...
您应该照常使用
Aggregate
,然后使用Where
忽略负余额。顺便说一句,在 LINQ 方法中使用具有副作用的函数(例如
Console.WriteLine
)是一种不好的做法。您最好首先执行所有 LINQ 聚合和过滤,然后编写foreach
循环以打印到控制台。You should use
Aggregate
as normal, then useWhere
to omit negative balances.BTW, using functions with side effects (such as
Console.WriteLine
) inside a LINQ method is bad practice. You're better off doing all of the LINQ aggregation and filtering first, then writing aforeach
loop to print to the console.用 for 循环替换聚合。
Replace aggregate with for loop.
您可能想要使用
TakeWhile().Aggregate()
并检查 take while 谓词中的余额。You probably want to use
TakeWhile().Aggregate()
and check the balance in the take while predicate.