Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you want to do this via CompareTo, you may need some more comlpex logic to handle comparing the parent trees. Below is a possible solution:</p> <pre><code>public virtual Int32 CompareTo(Person person2) { Stack&lt;Person&gt; parents1 = GetParents(this); Stack&lt;Person&gt; parents2 = GetParents(person2); foreach (Person parent1 in parents1) { Person parent2 = parents2.Pop(); // These two persons have the same parent tree: // Compare their ids if (parent1 == null &amp;&amp; parent2 == null) { return 0; } // 'this' person's parent tree is contained in person2's: // 'this' must be a parent of person2 else if (parent1 == null) { return -1; } // 'this' person's parent tree contains person2's: // 'this' must be a child of person2 else if (parent2 == null) { return 1; } // So far, both parent trees are the same size // Compare the ids of each parent. // If they are the same, go down another level. else { int comparison = parent1.id.CompareTo(parent2.id); if (comparison != 0) { return comparison; } } } // We should never get here anymore, but if we do, // these are the same Person return 0; } public static Stack&lt;Person&gt; GetParents(Person p) { Stack&lt;Person&gt; parents = new Stack&lt;Person&gt;(); // Add a null so that we don't have to check // if the stack is empty before popping. parents.Push(null); Person parent = p; // Recurse through tree to root while (parent != null) { parents.Push(parent); parent = parent.Parent; } return parents; } </code></pre> <p><strong>Update:</strong> Both parent-stacks now contain the original person, making the comparison logic a little easier.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload