从下面的模拟
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.But我的代码遍历整个array.How来终止它?
发布于 2009-12-03 19:56:12
在我看来,您需要一个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中有这样的东西,但我现在找不到了……
发布于 2009-12-03 19:55:05
您应该像往常一样使用Aggregate,然后使用Where忽略负余额。
顺便说一句,在LINQ方法中使用有副作用的函数(比如Console.WriteLine)是不好的做法。您最好先执行所有的LINQ聚合和过滤,然后编写一个foreach循环以打印到控制台。
发布于 2009-12-03 19:55:36
用for循环替换aggregate。
https://stackoverflow.com/questions/1839459
复制相似问题