Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# iterate over nested property lists recursively

Tags:

c#

recursion

foreach (TargetObject innerObject1 in complexObject.InnerObjects) { 
    foreach (TargetObject innerObject2 in innerObject1.InnerObjects) { 
        foreach (TargetObject innerObject3 in innerObject2.InnerObjects) { 
           yield return innerObject3;
        } 
        yield return innerObject2;
    } 
    yield return innerObject1;
 }

How can I do this cursively? I need to aggregate all instances of TargetObject trapped in these nested listed into one list. Here's an attempt that didn't work.

 public static IEnumerable<TargetObject> GetRecursively(params TargetObject[] startingObjects) 
    {
        foreach (TargetObject startingObject in startingObjects) 
        {
            foreach (TargetObject innerObject in GetRecursively(startingObject.InnerObjects.ToArray()))
            {
                yield return innerObject;
            }
            yield return startingObject;
        }
    }
like image 732
parliament Avatar asked Oct 09 '13 01:10

parliament


1 Answers

Like this -- yield startingObject, and call recursively for each item in InnerObjects:

public static IEnumerable<TargetObject> GetRecursively(TargetObject startingObject) 
{
    yield return startingObject;
    if (startingObject.InnerObjects != null)
        foreach (TargetObject innerObject in startingObject.InnerObjects.ToArray())
            foreach (TargetObject recursiveInner in GetRecursively(innerObject))
                yield return recursiveInner;
}

To support an array as the parameter, wrap a foreach around it:

public static IEnumerable<TargetObject> GetRecursively2(params TargetObject[] startingObjects)
{
    foreach (TargetObject startingObject in startingObjects)
    {
        yield return startingObject;
        if (startingObject.InnerObjects != null)
            foreach (TargetObject innerObject in startingObject.InnerObjects.ToArray())
                foreach (TargetObject recursiveInner in GetRecursively(innerObject))
                    yield return recursiveInner;
    }
}
like image 137
McGarnagle Avatar answered Sep 30 '22 17:09

McGarnagle