title: Linq .GroupBy .Where .Select new Grouping item
body: <p>I'm trying to build a change log query that pulls logs since last revision.</p>
  
  <p>I now need to consolidate the logs based on some rules.</p>
  
  <p>Here's my Changelog Model:</p>
  
  <pre><code>public abstract class ChangeLogObject : TrackedObject {
      /// &lt;summary&gt;
      /// Type of transaction that occured
      /// &lt;/summary&gt;
      public ChangeType ChangeType { get; set; }
  
      /// &lt;summary&gt;
      /// Original Id of the stateful object this changelog was created against
      /// &lt;/summary&gt;
      public long EntityId { get; set; }
  
  }
  public enum ChangeType {
      Created,
      Updated,
      Deleted
  }
  </code></pre>
  
  <p>So the steps I need to follow are:</p>
  
  <ol>
  <li><p>Get where Id > last revision</p></li>
  <li><p>Group By EntityId</p></li>
  <li><p>Don't bring back any groups where the entity has ChangeType.Created and ChangeType.Deleted</p></li>
  <li><p>Don't bring back ChangeType.Updated records if there's a ChangeType.Deleted but no ChangeType.Created (remove updated records from the group)</p></li>
  <li><p>Only bring back the last ChangeType.Updated record if there are multiples</p></li>
  <li><p>If the group contains ChangeType.Created and ChangeType.Updated then only bring back the last ChangeType.Updated but change it to ChangeType.Created</p></li>
  </ol>
  
  <p>This is how far I've got but I don't know how to 'bring back part of a group':</p>
  
  <pre><code>        var newChanges = 
              // 1. Get where greater than last revision
              srcSet.Where(x =&gt; x.Id &gt; lastRevision)
  
              // 2. Group by EntityId
              .GroupBy(x =&gt; x.EntityId)
  
              // 3. Don't bring back created and deleted (it's come and gone)
              .Where(x =&gt; !(x.Any(y =&gt; y.ChangeType == ChangeType.Created) &amp;&amp;
                          x.Any(y =&gt; y.ChangeType == ChangeType.Deleted)))
  
              // 4. Only bring back Deleted if no created (don't edit something you're about to delete)
              .Where(x =&gt; (!x.Any(y =&gt; y.ChangeType == ChangeType.Created) &amp;&amp; 
                          x.Any(y =&gt; y.ChangeType == ChangeType.Deleted)))
                          //create new grouping, but only use the delete record????
  
              //convert back to individual change logs
              .Select(x =&gt; x.ToList()
              //maybe order by ID?
              .OrderBy(y =&gt; y.Id));
  </code></pre>
  
  <p>For 4. How do I turn x into a new group with only the records/values that are ChangeType.Deleted if the group itself doesn't contain a ChangeType.Created but may contain ChangeType.Updated?</p>