Skip to content

Instantly share code, notes, and snippets.

@sudipto80
Created March 23, 2024 07:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sudipto80/1988caf8e5c91d67269eb7c1ca9ad39e to your computer and use it in GitHub Desktop.
Save sudipto80/1988caf8e5c91d67269eb7c1ca9ad39e to your computer and use it in GitHub Desktop.
Roslyn code to find out property names that starts with the classname
// 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