Skip to content

Instantly share code, notes, and snippets.

@dahlbyk
Created March 31, 2011 04:19
Show Gist options
  • Save dahlbyk/895806 to your computer and use it in GitHub Desktop.
Save dahlbyk/895806 to your computer and use it in GitHub Desktop.
Nested set model
public class NestedSetModelTest
{
public class Node
{
public Node(string value, params Node[] children)
{
Value = value;
Children = children;
}
public string Value { get; private set; }
public Node[] Children { get; private set; }
}
public void Test()
{
// Sample tree from http://en.wikipedia.org/wiki/Nested_set_model
var tree =
new Node("Clothing",
new Node("Men's",
new Node("Suits",
new Node("Slacks"),
new Node("Jackets")
)
),
new Node("Women's",
new Node("Dresses",
new Node("Evening Gowns"),
new Node("Sun Dresses")
),
new Node("Skirts"),
new Node("Blouses")
)
);
foreach (var e in GetSetEntries(0, 1, tree))
Console.WriteLine(e);
}
public IEnumerable<Tuple<string, int, int, int>> GetSetEntries(int depth, int left, Node node)
{
var right = left + 1;
foreach (var n in node.Children)
foreach (var e in GetSetEntries(depth + 1, right, n))
{
yield return e;
right = e.Item3 + 1;
}
yield return Tuple.Create(node.Value, left, right, depth);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment