Skip to content

Basic Querying

David West edited this page Aug 26, 2016 · 13 revisions

< 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.

Find a Single Node By Id

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;

The Item and Id Properties

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.

General LINQ Operations

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.

Hierarchical Properties and Built-In Queries

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]);

Entity Definitions >

Clone this wiki locally