首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >聚合中的C# -Termination ()

聚合中的C# -Termination ()
EN

Stack Overflow用户
提问于 2009-12-03 19:51:37
回答 4查看 301关注 0票数 2

从下面的模拟

代码语言:javascript
复制
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来终止它?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2009-12-03 19:56:12

在我看来,您需要一个Accumulate方法来生成一个新的累加值序列,而不是一个标量。如下所示:

代码语言:javascript
复制
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

代码语言:javascript
复制
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中有这样的东西,但我现在找不到了……

票数 5
EN

Stack Overflow用户

发布于 2009-12-03 19:55:05

您应该像往常一样使用Aggregate,然后使用Where忽略负余额。

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

票数 1
EN

Stack Overflow用户

发布于 2009-12-03 19:55:36

用for循环替换aggregate。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1839459

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档