mercredi 19 octobre 2022

Get class properties in string list in c#?

Please find the below entities :

public class Country
{
    public int Id;
    public string name;
    public string code;
}
public class City
{
    public int Id;
    public string name;
    public country {get;set;}
}
public class Person
{
    public int Id;
    public string name;
    public DateTime dob;
    public string gender;
    public city {get;set;}
}

I need to get all properties as string list as mentioned below:

"Id"
"name"
"dob"
"gender"
"city.Id"
"city.name"
"city.country.Id"
"city.country.name"
"city.country.code"

And my method to get property is

private List<string> GetProps(Type type)
{
    var result=new List<string>();
    var properties = type.GetProperties().ToDictionary(x => x, x => x.GetType().GetProperties());
    foreach (var item in properties)
    {
        result.Add(item.Key.ToString());
    }
    return result;
}

GetProps(typeof(Person)); // calling in main method;

The coming result is

"Id"
"name"
"dob"
"gender"
"city"

But my expected result is : "Id" "name" "dob" "gender" "city.Id" "city.name" "city.country.Id" "city.country.name" "city.country.code"

Please help :)





Aucun commentaire:

Enregistrer un commentaire