Hello stackoverflow community,
I have a fairly vexing issue that I'm trying to resolve, and would welcome some assistance or suggestions. Basically, I need to recursively walk through a complex object, and once I find the property (no matter how nested down it is), pull the data from that property.
The existing code I have that works (found here on stackoverflow) at least for the object, properties, and sub object properties is as follows:
public static void GetPropertyValue(Type type, string propertyName)
{
Console.WriteLine($"Describing type {type.Name}");
var propertyInfos = type.GetProperties();
foreach (var pi in propertyInfos)
{
Console.WriteLine($"Has property {pi.Name} of type {pi.PropertyType.Name}");
if (pi.PropertyType.IsClass && !pi.PropertyType.FullName.StartsWith("System."))
{
GetPropertyValue(pi.PropertyType, propertyName);
}
}
}
The problem is that it falls apart when there is a collection (ICollection, List, etc.,), basically any Enumerable type. It's not a type of Class nor starts with System. How do you tell the function the property type is a collection / enumerable type, and walk further into the object? Also, if nothing is found in that collection, do you have to walk backwards to the parent object? Lastly, are there any other complex types that should be accounted for as well?
NOTE, this code doesn't include checking the propertyName, JUST the recursive walking through of the object.
Thanks in advance for the help!