How to Aggregate with GroupBy and wait for results
<p>Say, for example, I'm keeping track of the distance each player has travelled for a cricket roster. I might have the following objects</p>

<ul>
<li>Trip (IList legs)</li>
<li>Leg (distance, duration, player and belongs to trip)</li>
<li>Player (belongs to team)</li>
<li>Team</li>
</ul>

<p>I would like to aggregate this data using Reactive Extensions. Here's my first attempt:</p>

<pre><code>var trips = new List&lt;Trip&gt;();

Observable.Return( trips )
  .SelectMany( trips =&gt; trips )
  .SelectMany( trip =&gt; trip.legs )
  .GroupBy( leg =&gt; leg.player.team )
  .Select( teamLegs =&gt; {
    var teamSummary = new {
      team = teamLegs.key,
      distance = 0M,
      duration = 0M
    }

    teamLegs.Sum( x =&gt; x.distance ).Subscribe( x =&gt; { teamSummary.distance = x; } )
    teamLegs.Sum( x =&gt; x.duration ).Subscribe( x =&gt; { teamSummary.duration = x; } )

    return teamSummary;
  })
  .Select(teamSummary =&gt; {
      // If I try to do something with teamSummary.distance or duration - the above
      // sum is yet to be completed 
  })

  // ToList will make the above sums work, but only if there's only 1 Select statement above
  .ToList()

  .Subscribe(teamSummaries =&gt; {
  });
</code></pre>

<p>How can I make sure that the sums are completed before the second Select() statement?</p>