【问题标题】:Find min and max of cumulative sum in Linq在 Linq 中查找累积和的最小值和最大值
【发布时间】:2022-12-31 00:35:45
【问题描述】:

我有以下功能,我用它来查找终端累计正值和负值,它正在工作:

public class CumulativeTotal
{
    [Test]
    public void CalculatesTerminalValue()
    {
        IEnumerable<decimal> sequence = new decimal[] { 10, 20, 20, -20, -50, 10 };

        var values = FindTerminalValues(sequence);
        Assert.That(values.Item1, Is.EqualTo(-20));
        Assert.That(values.Item2, Is.EqualTo(50));

        Assert.Pass();
    }

    public static Tuple<decimal,decimal> FindTerminalValues(IEnumerable<decimal> values)
    {
        decimal largest = 0;
        decimal smallest = 0;
        decimal current = 0;

        foreach (var value in values)
        {
            current += value;
            if (current > largest)
                largest = current;
            else if (current < smallest)
                smallest = current;
        }

        return new Tuple<decimal, decimal>(smallest,largest);
    }
}

但是,为了学习,我怎么能用Linq来实现呢?

我可以看到一个包裹MoreLinq,但不知道从哪里开始!

【问题讨论】:

  • 我可能混淆了术语,这本质上是一个分类帐和要添加的序列增量中的值。它至少是 -20 10 + 20 + 20 - 20 - 50 = -20(然后不会低于那个)
  • values.Aggregate((min: 0, max: 0), (ac, current) =&gt; (current &lt; ac.min ? current : ac.min, current &gt; ac.max : current : ac.max))
  • 您应该将 smallest 初始化为 decimal.MaxValue 并将 largest 初始化为 decimal.MinValue 这样,如果最大总和为负或最小总和为正,它仍然可以工作。
  • @AluanHaddad 那不是跟踪运行总和。
  • @juharr 我注意到他没有使用运行总和,所以我没有理会它。

标签: c# linq morelinq


【解决方案1】:

是的,你可以像这样使用MoreLinq,它有Scan方法。

public static Tuple<decimal, decimal> FindTerminalValues(IEnumerable<decimal> values)
{
    var cumulativeSum = values.Scan((acc, x) => acc + x).ToList();

    decimal min = cumulativeSum.Min();
    decimal max = cumulativeSum.Max();

    return new Tuple<decimal, decimal>(min, max);
}

Scan 扩展方法通过将函数应用于输入序列中的每个元素来生成新序列,并将前一个元素用作累加器。在本例中,该函数只是加法运算符,因此 Scan 方法生成一个输入序列的累加和序列。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    • 2013-11-12
    • 2022-06-10
    • 2017-04-20
    • 2018-05-03
    相关资源
    最近更新 更多