Created
March 23, 2024 07:52
-
-
Save sudipto80/1988caf8e5c91d67269eb7c1ca9ad39e to your computer and use it in GitHub Desktop.
Roslyn code to find out property names that starts with the classname
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// See https://aka.ms/new-console-template for more information | |
using Microsoft.CodeAnalysis.CSharp; | |
using Microsoft.CodeAnalysis.CSharp.Syntax; | |
public class Demo | |
{ | |
private static Dictionary<string, List<string>> _classWisePropMap | |
= new Dictionary<string, List<string>>(); | |
public static void ReportIssues() | |
{ | |
foreach(var key in _classWisePropMap.Keys) | |
{ | |
foreach(var v in _classWisePropMap[key]) | |
{ | |
if (v.StartsWith(key)) | |
{ | |
Console.WriteLine("Property '" + v + "' has the class name prefix '" + key + "'"); | |
} | |
} | |
} | |
} | |
public static void Main(string[] args) | |
{ | |
string code = @"public class Student { | |
public string StudentName {get;set;} | |
public string StudentMajor {get;set;} | |
public string StudentScore {get;set;} | |
public string Address {get;set;} | |
public List<string> OtherSubjects {get;set;} | |
"; | |
var root = CSharpSyntaxTree.ParseText(code).GetRoot(); | |
_classWisePropMap = | |
root.DescendantNodes() | |
.OfType<ClassDeclarationSyntax>() | |
.Select(t => new | |
{ | |
ClassName = t.Identifier.ValueText, | |
PublicPropertyNames = t.DescendantNodes().OfType<PropertyDeclarationSyntax>() | |
.Select(z => z.Identifier.ValueText).ToList() | |
}) | |
.ToLookup(t => t.ClassName) | |
.ToDictionary(t => t.Key, | |
t => t.SelectMany(m => m.PublicPropertyNames).ToList()); | |
ReportIssues(); | |
Console.ReadKey(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment