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

前端之家收集整理的这篇文章主要介绍了c#以递归方式迭代嵌套属性列表前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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;
        }
    }

解决方法

像这样 – 产生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;
    }
}
原文链接:https://www.f2er.com/csharp/244542.html

猜你在找的C#相关文章