Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Many thanks to Jon and to mquander - you guys gave me enough information to help me solve this in a proper, generic way. Here's my solution, a single generic extension method that converts objects into hierarchy form:</p> <pre><code>public static IEnumerable&lt;Node&lt;T&gt;&gt; Hierarchize&lt;T, TKey, TOrderKey&gt;( this IEnumerable&lt;T&gt; elements, TKey topMostKey, Func&lt;T, TKey&gt; keySelector, Func&lt;T, TKey&gt; parentKeySelector, Func&lt;T, TOrderKey&gt; orderingKeySelector) { var families = elements.ToLookup(parentKeySelector); var childrenFetcher = default(Func&lt;TKey, IEnumerable&lt;Node&lt;T&gt;&gt;&gt;); childrenFetcher = parentId =&gt; families[parentId] .OrderBy(orderingKeySelector) .Select(x =&gt; new Node&lt;T&gt;(x, childrenFetcher(keySelector(x)))); return childrenFetcher(topMostKey); } </code></pre> <p>Utilizes this small node class:</p> <pre><code>public class Node&lt;T&gt; { public T Value { get; private set; } public IList&lt;Node&lt;T&gt;&gt; Children { get; private set; } public Node(T value, IEnumerable&lt;Node&lt;T&gt;&gt; children) { this.Value = value; this.Children = new List&lt;Node&lt;T&gt;&gt;(children); } } </code></pre> <p>It's generic enough to work for a variety of problems, including my text file issue. Nifty!</p> <p>****UPDATE****: Here's how you'd use it:</p> <pre><code>// Given some example data: var items = new[] { new Foo() { Id = 1, ParentId = -1, // Indicates no parent Position = 0 }, new Foo() { Id = 2, ParentId = 1, Position = 0 }, new Foo() { Id = 3, ParentId = 1, Position = 1 } }; // Turn it into a hierarchy! // We'll get back a list of Node&lt;T&gt; containing the root nodes. // Each node will have a list of child nodes. var hierarchy = items.Hierarchize( -1, // The "root level" key. We're using -1 to indicate root level. f =&gt; f.Id, // The ID property on your object f =&gt; f.ParentId, // The property on your object that points to its parent f =&gt; f.Position, // The property on your object that specifies the order within its parent ); </code></pre>
 

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