title: LINQ to calculate a moving average of a SortedList<dateTime,double>
body: <p>I have a time series in the form of a <code>SortedList&lt;dateTime,double&gt;</code>. I would like to calculate a moving average of this series. I can do this using simple for loops. I was wondering if there is a better way to do this using linq.</p>
  
  <p>my version:</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  
  namespace ConsoleApplication1
  {
      class Program
      {
          static void Main(string[] args)
          {
              var mySeries = new SortedList&lt;DateTime, double&gt;();
              mySeries.Add(new DateTime(2011, 01, 1), 10);
              mySeries.Add(new DateTime(2011, 01, 2), 25);
              mySeries.Add(new DateTime(2011, 01, 3), 30);
              mySeries.Add(new DateTime(2011, 01, 4), 45);
              mySeries.Add(new DateTime(2011, 01, 5), 50);
              mySeries.Add(new DateTime(2011, 01, 6), 65);
  
              var calcs = new calculations();
              var avg = calcs.MovingAverage(mySeries, 3);
              foreach (var item in avg)
              {
                  Console.WriteLine("{0} {1}", item.Key, item.Value);                
              }
          }
      }
      class calculations
      {
          public SortedList&lt;DateTime, double&gt; MovingAverage(SortedList&lt;DateTime, double&gt; series, int period)
          {
              var result = new SortedList&lt;DateTime, double&gt;();
  
              for (int i = 0; i &lt; series.Count(); i++)
              {
                  if (i &gt;= period - 1)
                  {
                      double total = 0;
                      for (int x = i; x &gt; (i - period); x--)
                          total += series.Values[x];
                      double average = total / period;
                      result.Add(series.Keys[i], average);  
                  }
  
              }
              return result;
          }
      }
  }
  </code></pre>