How to remove a list of SyntaxNode from the Document using Roslyn code fix provider APIs?

浪子不回头ぞ 提交于 2019-12-06 06:24:45

The problem with your approach is that whenever you change the tree (using ReplaceNode() or RemoveNode()), it means all the nodes change as well. This is why your calls to RemoveNode() after ReplaceNode() don't do anything.

One way to fix this is to use TrackNodes(), so that you can find which nodes in the modified tree correspond to nodes in the original tree.

Uisng this, a method that replaces a sequence of nodes with a single node could look like this:

public static T ReplaceNodes<T>(
    this T root, IReadOnlyList<SyntaxNode> oldNodes, SyntaxNode newNode)
    where T : SyntaxNode
{
    if (oldNodes.Count == 0)
        throw new ArgumentException();

    var newRoot = root.TrackNodes(oldNodes);

    var first = newRoot.GetCurrentNode(oldNodes[0]);

    newRoot = newRoot.ReplaceNode(first, newNode);

    var toRemove = oldNodes.Skip(1).Select(newRoot.GetCurrentNode);

    newRoot = newRoot.RemoveNodes(toRemove, SyntaxRemoveOptions.KeepNoTrivia);

    return newRoot;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!