BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

LINQ
.NET 4.0+

A LINQ Style Cumulative Moving Average Operator

When working with series of numeric data that include large fluctuations, it can be difficult to spot trends. One way of processing such a series to make it easier is to apply a cumulative moving average. This article describes a LINQ style extension method to calculate such an average.

Calling the Method

We can now try the cumulative moving average, using the data from the table that appeared earlier in the article. Add the code below to the Main method of the console application to set up the sequence and average it. The method outputs the original values alongside the results after combining them using the Zip operator.

IEnumerable<double> values = new double[]
{
    1200, 1400, 1350, 2600,
    1400, 1550, 1600, 1725,
    1700, 450, 1800, 2150 
};

var averages = values.CumulativeMovingAverage();
var results = values.Zip(averages, (v, a) => new { Value = v, Average = a.ToString("F2") });

foreach (var result in results)
{
    Console.WriteLine(result);
}

/* OUTPUT

{ Value = 1200, Average = 1200.00 }
{ Value = 1400, Average = 1300.00 }
{ Value = 1350, Average = 1316.67 }
{ Value = 2600, Average = 1637.50 }
{ Value = 1400, Average = 1590.00 }
{ Value = 1550, Average = 1583.33 }
{ Value = 1600, Average = 1585.71 }
{ Value = 1725, Average = 1603.13 }
{ Value = 1700, Average = 1613.89 }
{ Value = 450, Average = 1497.50 }
{ Value = 1800, Average = 1525.00 }
{ Value = 2150, Average = 1577.08 }

*/
9 August 2015