在对象树中查找对象

Che*_*ese 0 c# windows tree recursion

你好,我有一个下一个对象:

public class Industry
{
    public int? id { get; set; }
    public int? parentId { get; set; }
    public string name { get; set; }
    public List<Industry> industryList { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

因此它用于创建分层对象,它可以具有任何级别计数.

我需要创建一个函数,在这个树中找到一个给定id的对象.

到目前为止我写过这个:

//IndustryList - is a fully created hirerchical object, the Root List of industries
//id - is a id of industry that i wish to find.
private Industry GetIndustryById(List<Industry> IndustryList, int? id)
    {
        if (id != null)
        {
            foreach (Industry industry in IndustryList)
            {
                if (industry.id == id)
                {
                    return industry;
                }
            }
            foreach (Industry industry in IndustryList)
            {
                if (industry.industryList != null)
                {
                    return GetIndustryById(industry.industryList, id);
                }
            }
        }
        return null;
    }
Run Code Online (Sandbox Code Playgroud)

问题是这个代码完美无缺,因为在某些项目上它返回null - 这是不可能的,因为如果我看到并且可以按下这个项目那么它就存在了.我发现我的代码到了

return null;
Run Code Online (Sandbox Code Playgroud)

这也是不正确的,因为id有价值!

我的错误在哪里?

加成:

当我第一次调用函数GetIndustryById(List IndustryList,int?id)时,IndustryList - 是一个非空的静态全局对象.然后递归开始遍历此全局对象中的所有List,以查找具有请求ID的Industry.

这个if,只检查我是否给出了正确的参数,但如果(id!= null){},ID将始终相同

Mat*_*son 5

我想这就是答案:

private Industry GetIndustryById(List<Industry> IndustryList, int? id)
{
    if (id != null)
    {
        foreach (Industry industry in IndustryList)
        {
            if (industry.id == id)
            {
                return industry;
            }
        }
        foreach (Industry industry in IndustryList)
        {
            if (industry.industryList != null)
            {
                // Here was your mistake. If you return GetIndustryById()
                // without checking for null first, you will return null
                // if that subtree doesn't contain the target, even if
                // a subsequent subtree does.

                var result = GetIndustryById(industry.industryList, id);

                if (result != null)
                    return result;
            }
        }
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)