title: Calculations on grouped rows using lambda functions in c#
body: <p>I am trying to calculate Best and Worst body measurement changes for people who go on a fitness trip.</p>
  <p>I have a database full of before and after body composition measurements for several people who go on various trips.  Every participant and every trip has an Id.  There are 3 types of readings, B(efore), M(iddle) and A(fter).  Here is an example of the data:</p>
  <pre><code>ParticipantId TripId Type  Weight   BodyFatPct
  1               2     B    195      22.8
  1               2     B    189.6    24.1
  1               2     A    186.6    21.2
  1               2     A    187.6    23.8
  2               3     B    199.2    23.7
  2               3     B    198.4    25.1
  2               3     A    193      22.4
  </code></pre>
  <p>Here is the class I'm using to represent the data:</p>
  <pre><code>    public partial class Detail
      {
          public int ParticipantId { get; set; }
          public int TripId { get; set; }
          public string Type { get; set; }
          public double? Weight { get; set; }
          public double? BodyFatPct { get; set; }
      }
  </code></pre>
  <p>Here is my highly inefficient C# code to calculate best and worst for weight and body fat.</p>
  <pre><code>List&lt;Detail&gt; result = new List&lt;Detail&gt;();
  
  var _result = result.GroupBy(x =&gt; new { x.ParticipantId, x.TripId });
  foreach(var res in _result)
  {
      var beforeHighWeight = res.Where(x =&gt; x.Type == &quot;B&quot;).Max(x =&gt; x.Weight);
      var beforeLowWeight = res.Where(x =&gt; x.Type == &quot;B&quot;).Min(x =&gt; x.Weight);
      var afterWeight = res.Where(x =&gt; x.Type == &quot;A&quot;).Min(x =&gt; x.Weight);
      var beforeHighFat = res.Where(x =&gt; x.Type == &quot;B&quot;).Max(x =&gt; x.BodyFatPct);
      var beforeLowFat = res.Where(x =&gt; x.Type == &quot;B&quot;).Min(x =&gt; x.BodyFatPct);
      var afterFat = res.Where(x =&gt; x.Type == &quot;A&quot;).Min(x =&gt; x.BodyFatPct);
      var BestWeightDiff = BeforeHighWeight - afterWeight;
      var WorstWeightDiff = BeforeLowWeight - afterWeight;
      var BestFatDiff = BeforeHighFat - afterFat;
      var WorstFatDiff = BeforeLowFat - afterFat;
  }
  </code></pre>
  <p>In actuality, I have about 15 fields to calculate, not just two.  Is there a lambda function that does row-wise calculations on grouped data?  Any help appreciated.</p>