mardi 28 septembre 2021

Loop through objects properties in an object

I have got an object like below

public class MainObj 
{
    public int BankDetailPercentage { get; set; }
    public int PersonalDetailPercentage { get; set; }
    public BankDetail BankDetail { get; set; }
    public PersonalDetail PersonalDetail { get; set; }
}
public class BankDetail
{
    public string Name { get; set; }
    public string Branch { get; set; }
    public string AccountNumber { get; set; }
}
public class PersonalDetail
{
    public string Name { get; set; }
    public string address { get; set; }
}

I need to loop through that MainObj Object and find how many properties of BankDetail and PersonalDetail objects are filled and on the basis of that I should set the percentage of filled properties in MainObj object's BankDetailPercentage and PersonalDetailPercentage fields and return it. How can I accomplish this, I have tried below but couldn't get how to do it

    public MainObject calculatePercentage(MainObject mainObject) 
    {
        int bdCount = 0, pdCount = 0, bdTotal = 3, pdTotal = 2;

        PropertyInfo[] properties = typeof(MainObject).GetProperties();
        foreach (var property in properties)
        {
            var value = property.GetValue(mainObject);
            if (property.Name == "BankDetail")
            {
              //
            }
        }
        return mainObject;
    }




Aucun commentaire:

Enregistrer un commentaire