c#以递归方式迭代嵌套属性列表

时间:2013-10-09 01:42:15

标签: 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;
 }

我怎么能这么做?我需要将列在这些嵌套列表中的TargetObject的所有实例聚合到一个列表中。这是一次无效的尝试。

 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;
        }
    }

1 个答案:

答案 0 :(得分:8)

像这样 - 产生startingObject,并递归调用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;
}

要支持数组作为参数,请在其周围包裹foreach

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;
    }
}