Developer
Developer

Reputation: 4331

Find object in tree of objects

Hello i have a next object:

public class Industry
{
    public int? id { get; set; }
    public int? parentId { get; set; }
    public string name { get; set; }
    public List<Industry> industryList { get; set; }
}

So it is used to create hierarchical object, it can have any level count.

I need to create function that finds in this tree an object with given id.

I have written this so far:

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

The problem is that this code works almoust perfect, because on some items it returns null - that is impossible, because if i see and can press this item then it exists. I found out that my code reaches

return null;

That also cannot be correct, because id had a value!

Where is my mistake?

ADDITION:

When i first time call the function GetIndustryById(List IndustryList, int? id) IndustryList - is a static global object that is not null. Then the recursion starts to go through all the List inside this global object to find Industry with requested id.

This if, just checks if i have given the right parameter, but the ID will always be the same if (id != null) { }

Upvotes: 0

Views: 531

Answers (1)

Matthew Watson
Matthew Watson

Reputation: 109742

I think this is the answer:

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

Upvotes: 5

Related Questions