0

I have a method that looks like this:

public string Bid(AdapterRequest adapterRequest)
{
    string property = "adapterRequest.Lead.Contact.ZipCode";
    string zipCode = ???
}

How can I get the value of adapterRequest.Lead.Contact.ZipCode from the string value?

Scott
  • 13,735
  • 20
  • 94
  • 152
  • 1
    and this, which covers nested properties / complex types specifically http://stackoverflow.com/questions/366332/best-way-to-get-sub-properties-using-getproperty – James Gaunt Feb 04 '14 at 18:59
  • @JamesGaunt - the question you linked was exactly what I needed. Thanks. – Scott Feb 04 '14 at 20:06

2 Answers2

1

You can use reflection with recursion:

public string Bid(AdapterRequest adapterRequest)
{
    string propertyChain = "Lead.Contact.ZipCode";
    string zipCode = ResolvePropertyChain(propertyChain.Split('.').ToList(), adapterRequest) as string;
    // ... assuming other logic exists here ...
}

public object ResolvePropertyChain(List<string> propertyChain, object source)
{
    object propertyValue = null;

    if (source != null)
    {
        propertyValue = source.GetType().GetProperty(propertyChain[0]).GetValue(source, null);

        if (propertyValue != null && propertyChain.Count > 1)
        {
            List<string> childPropertyChain = new List<string>(propertyChain);
            childPropertyChain.RemoveAt(0);
            propertyValue = ResolvePropertyChain(childPropertyChain, propertyValue);
        }
    }

    return propertyValue;
}
McAden
  • 13,714
  • 5
  • 37
  • 63
-3
string zipCode = (string)adapterRequest.GetType().GetProperty(property).GetValue(adapterRequest, null);

Note that this will not work in your case since you have an object herarchy, but you can split the property into parts and get objects one by one and repeat the query for next part on the latest retrieved object - GetType will work on a non null value.

Bogdan
  • 484
  • 2
  • 7