title: Keep structured trivia when removing a node
body: <p>Is there an easy way to remove a SyntaxNode (i.e. a method) from the tree, but keeping the structured trivia?</p>
  
  <p>In the following code I want to remove MethodA:</p>
  
  <pre><code>public class Sample 
  { 
    #region SomeRegion 
    public void MethodA() 
    { 
  
    }
    #endregion 
  } 
  </code></pre>
  
  <p>I use a CSharpSyntaxRewriter to rewrite the SyntaxTree. In the VisitMethodDeclaration method, I simply return null for MethodA. The problem with this approach is that the StructuredTrivia of the #region tag is also removed. This is the result result: </p>
  
  <pre><code>public class Sample 
  { 
    #endregion 
  }
  </code></pre>
  
  <p>In my CSharpSyntaxRewriter:  </p>
  
  <pre><code>public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node) 
  { 
     if (...) 
        return null; 
     else 
        return node; 
  } 
  </code></pre>
  
  <p>EDIT:
  As mentioned in one of the answers below, I could use SyntaxNode.RemoveNodes with the SyntaxRemoveOptions.KeepDirectives option. This solution has two big downsides:</p>
  
  <ol>
  <li>I need to know which SyntaxNode types can contain this child type. For example a method can be declared in a Struct, Class, Interface, etc ... Which means I need to do the filtering on multiple locations.</li>
  <li>I loose the ability to build the Syntax Tree from the bottom up. This gives problems when comparing SyntaxTree objects. All subsequent calls to the visitor methods already see the new nodes that are created in the "RemoveNodes" method.
  With the SyntaxNode.RemoveNodes method it's possible to specify SyntaxRemoveOptions.KeepDirectives, but is this also possible with CSharpSyntaxRewriter?</li>
  </ol>
  
  <p>EDIT2: Here is some code with what I'm trying to do: <a href="https://dotnetfiddle.net/1Cg6UZ" rel="nofollow">https://dotnetfiddle.net/1Cg6UZ</a></p>