Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the full name of a nested property and its parents

How can I get the full name of a nested property by its parent using reflection in C#? I mean, for example we have this classes:

public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public DateTime? DateOfBirth { get; set; }
    public Grade Grade { get; set; }
}

public class Grade
{
    public int GradeId { get; set; }
    public string GradeName { get; set; }
    public string Section { get; set; }
    public GradGroup GradGroup { get; set; }
}

public class GradGroup
{
    public int Id { get; set; }
    public string GroupName { get; set; }
}

I have "GradGroup" and Student as method parameters and want "Grade.GradeGroup" as output:

public string GetFullPropertyName(Type baseType, string propertyName)
    {
        // how to implement that??
    }

Call the method:

GetFullPropertyName(typeof(Student), "GradeGroup"); // Output is Grade.GradeGroup
like image 406
zmovahedi Avatar asked Dec 14 '22 17:12

zmovahedi


2 Answers

The property may not be unique as it might exist on several components so you should return an IEnumerable<string>. That being said you can traverse the property tree using GetProperties of Type:

public static IEnumerable<string> GetFullPropertyName(Type baseType, string propertyName)
{
    var prop = baseType.GetProperty(propertyName);
    if(prop != null)
    {
        return new[] { prop.Name };
    }
    else if(baseType.IsClass && baseType != typeof(string)) // Do not go into primitives (condition could be refined, this excludes all structs and strings)
    {
        return baseType
            .GetProperties()
            .SelectMany(p => GetFullPropertyName(p.PropertyType, propertyName), (p, v) => p.Name + "." + v);
    }
    return Enumerable.Empty<string>();
}
like image 140
Titian Cernicova-Dragomir Avatar answered Jan 14 '23 20:01

Titian Cernicova-Dragomir


  • Use reflection to find all properties of a type
  • Use bread first search to find the nested property with given name
  • Concatenate the property names you found in the path with a "."

Here are some useful references

  • String.Join
  • System.Reflection.PropertyInfo
  • Breadth-first traversal
like image 37
Muhammad Hasan Khan Avatar answered Jan 14 '23 20:01

Muhammad Hasan Khan