我不觉得有什么样构建成标准的LINQ方法库。但是您可以轻松创建自己的扩展方法。我称之为AggregateUntil
:
public static class EnumerableExtensions
{
public static IEnumerable<TResult> AggregateUntil<TSource, TAccumulate, TResult>(
this IEnumerable<TSource> source,
TAccumulate seed,
Func<TAccumulate, TSource, TAccumulate> func,
Func<TAccumulate, bool> condition,
Func<TAccumulate, TResult> resultSelector
)
{
TAccumulate acc = seed;
TAccumulate newAcc;
foreach(var item in source)
{
newAcc = func(acc, item);
if(!condition(newAcc))
{
yield return resultSelector(acc);
acc = func(seed, item);
}
else
{
acc = newAcc;
}
}
yield return resultSelector(acc);
}
}
现在让我们使用它。首先,只需要乘法,只要他们遇到了< 15
条件:
var grouped
= values.AggregateUntil(1, (a,i) => a * i, a => a < 15, a => a).ToList();
返回List<int>
有3项:12
,14
,14
。这就是你需要的。但是现在让我们把每个乘法中汇总的项目数量。这很容易使用匿名类型::
int[] values = { 1, 3, 4, 2, 7, 14 };
var grouped
= values.AggregateUntil(
new { v = 1, c = 0 },
(a, i) => new { v = a.v * i, c = a.c + 1 },
a => a.v < 15,
a => a).ToList(); ;
返回正是你需要的:
你有什么特别的理由需要使用LINQ吗?似乎你可以轻松实现这一点,只是通过阵列。 –