0

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!

  • Well an interface will break your code and what do you want to do with a collection? A collection IS an object and also contains additional objects. Do you want the property on the collection class (eg propertyName = "Count" eg List.Count) or do you all the values of all the items in the collection if they have that property name? – Erik Philips Jul 08 '22 at 22:17
  • Hi @ErikPhilips, thank you for the information. Yes that it is correct, looking to walk though the collection for each of its properties, to find the one in question. The property could be a string, int, other primitive types, etc. It appears someone else had a similar problem, which they resolved here: https://stackoverflow.com/questions/20554103/recursively-get-properties-child-properties-of-a-class Thanks again! – BatmanPriddy Jul 09 '22 at 15:12

0 Answers0