C#Linq聚合中间值

Ada*_*dam 12 .net c# linq arrays

给定一组正数和负数是否有一个可以获得中间值的Linq表达式?

例如

var heights = new List<int>();    
var numbers = new [] { 5, 15, -5, -15 };    
var curHeight = 0;

foreach (var number in numbers)
{
    curHeight = curHeight + number;
    heights.add(curHeight);
}
Run Code Online (Sandbox Code Playgroud)

此功能将返回 [5, 20, 15, 0]

聚合可以以相同的方式使用,它将通过此​​序列

numbers.aggregate((a, b) => a + b);
0 + 5 = 5, 5 + 15 = 20, 20 - 5 = 15, 15 - 15 = 0
Run Code Online (Sandbox Code Playgroud)

我的问题是,有没有办法使用聚合或其他一些方法来[5, 20, 15, 0]返回中间值?

Eri*_*ert 14

您需要的是聚合的自定义版本:

public static IEnumerable<R> AggregateSequence<A, R>(
  this IEnumerable<A> items,
  Func<A, R, R> aggregator,
  R initial)
{
  // Error cases go here.
  R result = initial;
  foreach(A item in items)
  {
    result = aggregator(item, result);
    yield return result;
  }
}
Run Code Online (Sandbox Code Playgroud)

这是解决您的具体问题的一般机制:

public static IEnumerable<int> MovingSum(this IEnumerable<int> items)
{
  return items.AggregateSequence( (item, sum) => item + sum, 0 );
}
Run Code Online (Sandbox Code Playgroud)

现在你可以解决你的问题了

mySequence.MovingSum().Max();
Run Code Online (Sandbox Code Playgroud)