C# - 聚合中的终止()

use*_*675 2 c# extension-methods

从以下模拟

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;
 }
);
Run Code Online (Sandbox Code Playgroud)

我想终止聚合when the balance is less than the withdrawal.但我的代码遍历整个数组.如何终止它?

Jon*_*eet 5

在我看来,你想要一个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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以申请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);
Run Code Online (Sandbox Code Playgroud)

我可以发誓在正常的LINQ to Objects中有这样的东西,但我现在找不到它......