Sort and remove (unused) using statements Roslyn script/code?

后端 未结 5 644
旧时难觅i
旧时难觅i 2020-12-31 09:34

Sort and remove (unused) using statements Roslyn script/code? I\'m looking for some .NET/Roslyn (compiler as service) code that can run through a project and sort and remov

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-31 09:38

    I use this the following extension method to sort usings

    internal static SyntaxList Sort(this SyntaxList usingDirectives, bool placeSystemNamespaceFirst = false) =>
        SyntaxFactory.List(
            usingDirectives
            .OrderBy(x => x.StaticKeyword.IsKind(SyntaxKind.StaticKeyword) ? 1 : x.Alias == null ? 0 : 2)
            .ThenBy(x => x.Alias?.ToString())
            .ThenByDescending(x => placeSystemNamespaceFirst && x.Name.ToString().StartsWith(nameof(System) + "."))
            .ThenBy(x => x.Name.ToString()));
    

    and

    compilationUnit = compilationUnit.WithUsings(SortUsings(compilationUnit.Usings))
    

提交回复
热议问题