C#-聚合终止()
从下面的模拟C#-聚合终止(),c#,extension-methods,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
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;
}
);
当余额小于取款时,我想终止聚合
。但是我的代码会遍历整个数组。如何终止它?您应该像正常情况一样使用聚合,然后使用Where
忽略负余额
顺便说一句,在LINQ方法中使用具有副作用的函数(例如Console.WriteLine
)是一种糟糕的做法。您最好先执行所有LINQ聚合和筛选,然后编写一个foreach
循环以打印到控制台。将聚合替换为for循环。在我看来,您需要一个累积
方法,该方法生成一个新的累积值序列,而不是一个标量。大概是这样的:
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;
}
}
我可以发誓在普通LINQ to对象中有类似的东西,但我现在找不到它…您可能想使用TakeWhile().Aggregate()
并检查take while谓词中的平衡。我认为这不是OP想要的答案。他想检查负余额,而不是忽略它。但余额只在聚合后出现-这就是为什么我将TakeWhile放在它后面的原因。。。。但正如您所指出的,聚合将返回一个标量。嗯,你不能用标量值,乔恩;pDoh。与“聚合并返回新值作为序列”运算符混淆,其名称我目前已忘记。使用新运算符修复。。。我仍然希望在F#-库的某个地方有一个现有的操作符,这个函数叫做“scan”(Microsoft.FSharp.Collections.Seq.scan)。我认为在.Net框架中没有实现。很抱歉偏离主题。。。当我复制此代码并粘贴到VS2005中时。。。我在不同的地方发现语法错误。。。但是我可以看到这个代码对你有用。。。我是不是错过了什么。。。我使用VS2005和.NET2.0
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);