How to find an object property value from a nested objected group using a string as the property name?
asp.net-mvc-3, c#
Solution
Based on classes you showed in your question, you would need a recursive call to iterate your object properties. How about something you can reuse:
object GetValueFromClassProperty(string propname, object instance)
{
var type = instance.GetType();
foreach (var property in type.GetProperties())
{
var value = property.GetValue(instance, null);
if (property.PropertyType.FullName != "System.String"
&& !property.PropertyType.IsPrimitive)
{
return GetValueFromClassProperty(propname, value);
}
else if (property.Name == propname)
{
return value;
}
}
// if you reach this point then the property does not exists
return null;
}
`propname` is the property you are searching for. You can use is like this:
var val = GetValueFromClassProperty("Shape", myCar );
Problem
I have a nested set of objects ie some properties are custom objects. I would like to get a object property value within the hierarchy group using a string for the property name, and some form of "find" method to scan the hierarchy to find a property with matching name, and get its value. Is this possible and if so how? Many thanks. EDIT Class definition may be in pseudocode: ``` Class Car Public Window myWindow() Public Door myDoor() Class Window Public Shape() Class Door Public Material() Car myCar = new Car() myCar.myWindow.Shape ="Round" myDoor.Material = "Metal" ``` All a little contrived, but could I "find" the value of the "Shape" property by using the magic string "Shape" in some form of find function, starting from the top object. ie: ``` string myResult = myCar.FindPropertyValue("Shape") ``` Hopefully myResult = "Round". This is what I am after. Thanks.