C# help - finding parent of list items

Soldato
Joined
1 Feb 2006
Posts
8,188
Hi,

Hopefully I can explain the problem well enough. I have a hierarchy of terms for example:

L1
L1 -> L2
L1 -> L2 -> L3
L1 -> L2 -> L3 -> Ln

Each term has a property called 'Parent'. What is the best way to return the L1 and L2 terms for every single term.

If I am currently at location L1, I just need L1.Name returned
If I am currently at location L2, I just need L1.Name and L2.Name returned
...
for every other location I need L1.Name and L2.Name

What would the quickest way of finding these values be?

This is my code so far but I think its not good.
Code:
private Term GetParent(Term t)
        {
            if (t.Parent == null)
            {
                // this is L1
                return t;
            }
            else if (t.Parent.Parent == null)
            {
                // this is L2
                return t;
            }
            else
            {
                return GetParent(t.Parent);
            }
        }

This code will either return an L1 or L2 and then I can check the returned value to see if it has a parent. If it does then I know the returned term was L2.

Important to note that there will be multiple terms at each of the levels.
 
I'd probably add a couple of properties like this. Not tested, might not work...

Code:
public Term L1Parent
{
     get
          {				
               for (Term t = Parent; t != null; t = t.Parent)	
               {
                    if (t.Parent == null) return t;
               }
		
               return null;
          }
}

public Term L2Parent
{
     get
          {			
               for (Term t = Parent; t != null; t = t.Parent)	
               {
                    if (t.Parent != null && t.Parent.Parent == null) return t;
               }
               return null;
          }
}

EDIT: Change "for (t = Parent..." to "for (t = this...") if you want them to return themselves if they are L1 or L2.
 
Last edited:
Returns a list containing all parents of the supplied Term (untested!):

Code:
        private List<Term> GetParents(Term t)
        {
            List<Term> terms = new List<Term>();

            while (t.Parent != null)
            {
                terms.Add(t.Parent);
                t = t.Parent;
            }

            return terms;
        }
 
Back
Top Bottom