递归查找对象的孩子C#

时间:2018-08-24 13:54:25

标签: c# recursion

我想问你通过父母的每个孩子对象最有效的方法是什么。例如,我有一个类:

public class Asset
{
    public string Id { get; set; }

    public Asset Child { get; set; }
}

static void Main(string[] args)
{
     var x = new Asset() { Id = "1" };
     var y = new Asset() { Id = "2" };
     var z = new Asset() { Id = "3" };

     x.Child = y;
     y.Child = z;
     z.Child = null;

     var listOfChildItems = new List<Asset>();
     listOfChildItems = GetAllChildren(x);
}

static List<Asset> GetAllChildren(Asset asset)
{
   // TODO:
}

此类可能包含包含另一个孩子的Child,依此类推。因此,我要递归获取子项的子项的整个列表,直到子项不等于null。

4 个答案:

答案 0 :(得分:3)

class Asset
{
    public Asset Child { get; set; } = null;
}

static void main (string[] args) 
{
     List<Asset> children = new List<Asset>();
     Asset asset = new Asset();
     while (asset.Child != null) 
     {
         asset = asset.Child;
         children.Add(asset);
     }
     //asset is now the bottom most child
}

答案 1 :(得分:0)

docker commit hw_container hw_image

答案 2 :(得分:0)

public class Asset
{
    public Asset Child { get; set; }

    public List<Asset> GetChildren()
    {
        return GetChildrenInternal(new List<Asset>(), this);
    }

    private List<Asset> GetChildrenInternal(List<Asset> children, Asset parent)
    {
        if (parent.Child?.Child != null)
        {
            children.Add(parent.Child);
            GetChildrenInternal(children, parent.Child);
        }

        return children;
    }
}

答案 3 :(得分:0)

public static IEnumerable<T> GatherChild<T>(this T value, Func<T, T> selector)
    where T : class
{
    while (!(value is null))
    {
        yield return value;
        value = selector(value);
    }
}

public static IEnumerable<T> GatherSelfAndChildren<T>(this T value, Func<T, IEnumerable<T>> selector) => 
    selector(value).SelectMany(x => GatherSelfAndChildren(x, selector)).Prepend(value);

public static IEnumerable<T> GatherChildren<T>(this T value, Func<T, IEnumerable<T>> selector) => 
    selector(value).SelectMany(x => x.GatherSelfAndChildren(selector));