Home > Back-end >  Loop through objects properties in an object
Loop through objects properties in an object

Time:09-29

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;
    }

CodePudding user response:

First you will need to get the instance of the object in question (which you have done in your code above.

var value = property.GetValue(mainObject);

Then you need to count how many properties are contained in that object. To do that we need to first get the properties.

var subProperties = property.PropertyType.GetProperties();
var propertyCount = subProperties.Length;

Now we need to check each of those properties to see if a value is set.

var populatedCount = 0;

foreach (var subProperty in subProperties)
{
    if (!string.IsNullOrEmpty(subProperty.GetValue(value)))
    {
        populatedCount  ;
    }
}

Then take the percentage.

var percentage = (float)populatedCount / propertyCount;
  • Related