繁体   English   中英

聚集()中的C#-终止

[英]C# -Termination in 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;
 }
);

我想when the balance is less than the withdrawal提款额when the balance is less than the withdrawal终止聚合when the balance is less than the withdrawal但是我的代码遍历了整个数组,如何终止它?

在我看来,您想要一种Accumulate方法,该方法可以产生新的累积值序列,而不是标量。 像这样:

public static IEnumerable<TAccumulate> SequenceAggregate<TSource, TAccumulate>(
    this IEnumerable<TSource> source,
    TAccumulate seed,
    Func<TAccumulate, TSource, TAccumulate> func)
{
    TAccumulate current = seed;
    foreach (TSource item in source)
    {
        current = func(current, item);
        yield return current;
    }
}

然后,您可以应用TakeWhile

int[] amountWithdrawal = { 10, 20, 30, 140, 50, 70 };

var query = amountWithdrawal.SequenceAggregate(100, (balance, withdrawal) => 
{
  Console.WriteLine("balance :{0},Withdrawal:{1}", balance, withdrawal);
  return balance - withdrawal;
}).TakeWhile (balance => balance >= 0);

我本可以宣誓在普通的LINQ to Objects中有这样的东西,但目前无法找到...

您应该照常使用“ Aggregate ”,然后使用“ Where忽略负余额。

顺便说一句,在LINQ方法内部使用具有副作用的函数(例如Console.WriteLine )是不好的做法。 您最好先进行所有LINQ聚合和过滤,然后编写一个foreach循环以打印到控制台。

将聚合替换为for循环。

您可能要使用TakeWhile().Aggregate()并检查谓词中take的余额。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM