title: Entity Framework Core: Group by using calculated field
body: <p>I'm trying to write a query. What I have so far is shown below.</p>
  <pre><code>var x = from d in DbContext.StorageDetails
  
          let state = (d.ReleaseDate.HasValue &amp;&amp; d.ReleaseDate &lt; date) || (d.TakeOrPayEndDate.HasValue &amp;&amp; d.TakeOrPayEndDate &lt; date) ?
                  StorageState.Closed :
                  (d.RailcarNumber == null || d.RailcarNumber == string.Empty) ?
                      d.TakeOrPayStartDate.HasValue ? StorageState.TakeOrPay : StorageState.Open :
                      (d.ArrivalDate.HasValue &amp;&amp; d.ArrivalDate &lt;= date) ? StorageState.Filled : StorageState.EnRoute
  
          group d by new
          {
              d.CustomerId,
              d.Customer.Name,
              d.LocationId,
              d.Location.City,
              d.Location.State
          } into g
  
          select new
          {
              // ...
          };
  </code></pre>
  <p>The part that's giving me trouble is that I want to include the calculated <code>state</code> value with each item. I don't want to group by this value but I want to be able to sum it.</p>
  <pre><code>// Note: This is after my group statement
  select new
  {
      // state is a let variable and not part of x!
      TotalOpen = g.Sum(x =&gt; x.state == StorageState.Open),
      TotalClosed = g.Sum(x =&gt; x.state == StorageState.Closed),
      // Etc.
  };
  </code></pre>
  <p>Is there a way to do this? I don't seem able to <code>select</code> my own set of columns prior to <code>group by</code>. How can I insert this calculated field into each item?</p>
  <p><em>Note: <code>StorageState</code> is an enum. I can just as easily cast it to an <code>int</code> in all of these expressions. I can figure that part out, but figuring it out is separate from my question here.</em></p>