Path: redb/redb.Examples/Examples/E099_TreeQueryLevel.cs
Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb
Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E099_TreeQueryLevel.cs
----
using System.Diagnostics;
using redb.Core;
using redb.Examples.Models;
using redb.Examples.Output;
namespace redb.Examples.Examples;
///
/// Filter tree nodes by level.
/// WhereLevel finds nodes at specific depth from root.
///
[ExampleMeta("E099", "Tree Query - By Level", "Trees",
ExampleTier.Free, 2, "Tree", "TreeQuery", "WhereLevel", "Pro")]
public class E099_TreeQueryLevel : ExampleBase
{
public override async Task RunAsync(IRedbService redb)
{
var sw = Stopwatch.StartNew();
// Find root first - use TreeQuery!
var roots = await redb.TreeQuery()
.Where(d => d.Code == "CORP")
.Take(1)
.ToListAsync();
if (roots.Count == 0)
{
return Ok("E099", "Tree Query - By Level", ExampleTier.Free, sw.ElapsedMilliseconds, 0,
["No tree found. Run E090 first."]);
}
var rootId = roots[0].Id;
var query = redb.TreeQuery(rootId, maxDepth: 5)
.WhereLevel(2);
//var sql = query.ToSqlString();
//Console.WriteLine(sql);
// Find nodes at level 2 (departments under offices)
var level2 = await query
.WhereLevel(2)
.ToListAsync();
sw.Stop();
var names = level2.Select(n => $"{n.Name} ({n.Props.Code})").ToArray();
return Ok("E099", "Tree Query - By Level", ExampleTier.Free, sw.ElapsedMilliseconds, level2.Count,
[
"Filter: WhereLevel(2) - departments under offices",
$"Found: {string.Join(", ", names)}"
]);
}
}