-
Notifications
You must be signed in to change notification settings - Fork 25
Basic Querying
< Creating Your First Entity Tree
Continuing with our first entity tree (built with nodes of concrete type ReadonlyEntityTreeNode<int, Category>), let's take a look at the most common queries we can perform.
All examples below assume the variable root holds our root node.
If we want to get a single node with a known entity id (in this case, a CategoryId of 7), use the indexer operator like this:
var thingsNode = root[7];
Here, we're starting from the root and searching downward for the first (and ostensibly only) node whose entity id is 7.
If no node satisfies this condition, a null is returned;
On any EntityTreeNode object, the core entity object can be accessed through the Item property.
For example:
var mathName = root[19].Item.Name; // "Math";
var mathId = root[19].Item.CategoryId; // 19
The EntityTreeNode class has the shortcut property Id to make the second example above even simpler:
var mathId = root[19].Id; // 19
This is made possible by the fact that the tree knows (thanks to our root node constructor) that Category.CategoryId represents our core entity id.
As demonstrated earlier in the Entity Tree Overview, we can invoke any LINQ operation directly on a single node in the tree to return an enumerable sequence of nodes. By default, the enumerator will begin with the given node and continue with descendant nodes in pre-order (depth-first) traversal order.
For example, to select all entity ids in pre-order traversal:
var allIds = root.Select(node => node.Id);
Alternate parameterized enumerators will be introduced in a later section.
The following code snippets illustrate various properties and some useful pre-defined queries:
var current = root.First(n => n.Item.Name == "Places");
var parent = current.Parent;
var children = current.Children;
var descendants = current.SelectDescendants();
var leaves = current.SelectLeaves();
var siblings = current.SelectSiblings();
var siblingsBefore = current.SelectSiblingsBefore();
var siblingsAfter = current.SelectSiblingsAfter();
var pathUpward = current.SelectPathUpward(); // all nodes from self to root
var pathDownward = current.SelectPathDownward(); // all nodes from root to self
var ancestorsUpward = current.SelectAncestorsUpward();
var ancestorsDownward = current.SelectAncestorsDownward();
bool isRoot = current.IsRoot;
bool isLeaf = current.IsLeaf;
int level = current.Level; // note: root is level 0
int depth = root.Depth; // i.e. max level of the tree
bool isDescendant = current.IsDescendantOf(root[22]);
bool isAncestor = current.IsAncestorOf(root[15]);
bool isSibling = current.IsSiblingOf(root[12]);