title: Use LINQ to load cumulative average into MVC model
body: <p>Writing a stats web site for church softball team.</p>
  
  <p>I have a SQL view that calculates the batting average per game from stats in a table. I use that view to build a model in MVC called PlayerStats.</p>
  
  <p>I want to create and load data into a model that looks like this:</p>
  
  <pre><code>public class BattingAverage
  {
      [Key]
      public int stat_id { get; set; }
      public int player_id { get; set; }
      public decimal batting_avg { get; set; }
      public decimal cumulative_batting_avg { get; set; }
  }
  </code></pre>
  
  <p>In my controller I am doing this:</p>
  
  <pre><code>var model = (from s in PlayerStats
              where s.season_id == sid &amp;&amp; s.player_id == pid
              orderby s.game_no
              select g).AsEnumerable()
              .Select(b =&gt; new BattingAverage
              {
                  stat_id = b.stat_id,
                  player_id = b.player_id,
                  batting_avg = b.batting_avg,
                  cumulative_batting_avg = ***[[ WHAT TO DO HERE?? ]]***
              });
  </code></pre>
  
  <p>I don't know how to calculate that cumulative average to load into my model. The end goal is to Json.Encode the model data for use in AmCharts.</p>
  
  <p>UPDATE - I tried this:</p>
  
  <pre><code>cumulative_batting_avg = getCumulativeAvg(sid, pid, b.game_no)
  </code></pre>
  
  <p>And my function:</p>
  
  <pre><code>public decimal getCumulativeAvg(int season_id, int player_id, int game_no)
      {
          var averages = PlayerStats.Where(g =&gt; g.season_id == season_id &amp;&amp; g.player_id == player_id &amp;&amp; g.game_no &lt;= game_no).ToArray();
          var hits = averages.Select(a =&gt; a.Hits).Sum();
          var atbats = averages.Select(a =&gt; a.AtBats).Sum();
  
          if (atbats == 0)
          {
              return 0.0m;    // m suffix for decimal type
          }
          else
          {
              return hits / atbats;
          }
      }
  </code></pre>
  
  <p>This returned a correct average in the first row, but then zeroes for the rest. When I put a break on the return, I see that hits and atbats are properly accumulating inside the function, but for some reason the avg isn't being added to the model. What am I doing wrong?</p>