Curtis
Curtis

Reputation: 411

How do I loop through the sub property of a class?

I have a client class and one of the properties is Emails which is a list of strings. I can loop through the properties of the class to output the values, but when it gets to the Emails property it doesn't loop through the emails because it needs to do another loop through the list.

foreach (PropertyInfo prop in oClient.GetType().GetProperties())
{
    if (prop.Name.ToUpper().ToString() == "EMAILS")
    {
        //need code to loop through emails
    }
    else
    {
        Response.Write("<b>" + prop.Name.ToString() + "</b>: " + prop.GetValue(oClient, null) + "<br />");
    }
}

Upvotes: 0

Views: 188

Answers (1)

Rup
Rup

Reputation: 34408

You can read the value of Emails using

Object emails = prop.GetValue(oClient, null);

and then iterate through that, e.g.

IEnumerable<String> emailsEnumerable = emails as IEnumerable<String>;
if (emailsEnumerable != null) {
    foreach(string emailValue in emailsEnumerable) {
        // ...
    }
}

Upvotes: 2

Related Questions