Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have developed the class to implement object tree. Here is the simplest example:
public class TreeBO
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public List<treebo> Nodes { get; set; }

            public TreeBO()
            {
                Nodes=new List<treebo>();
            }

            
        }
</treebo></treebo>


Then I desided to write the method for searching tree node by id:
public TreeBO Find(int id)
            {
                TreeBO treeBo = null;
                Find(this, id, ref treeBo);
                return treeBo;
            }

private void Find(TreeBO treeBo, int id, ref TreeBO temp)
            {
                if(treeBo!=null&&temp==null)
                {
                    if (treeBo.ID == id)
                        temp=treeBo;
                    else
                    {
                        if(treeBo.Nodes.Count>0)
                        {
                            foreach (var child in treeBo.Nodes)
                            {
                                Find(child, id, ref temp);
                            }
                        }
                    }
                }
            }


I doubt this way is the most effective. May be anybody knows another solution?
Posted

1 solution

That's not too bad. The one performance related change I would make is to change this:

C#
foreach (var child in treeBo.Nodes)
{
    Find(child, id, ref temp);
}


to this:

C#
foreach (var child in treeBo.Nodes)
{
    Find(child, id, ref temp);
    if (temp != null) break;
}


If you've already found the match then there's no need to continue the loop, is there?

A style change I would make would be to change Find to return a node instead of taking a ref param as the return value, but that's just a personal preference thing.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900