Path: redb/redb.Examples/Examples/E112_TreeStats.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/E112_TreeStats.cs
----
using System.Diagnostics;
using redb.Core;
using redb.Core.Models.Contracts;
using redb.Core.Models.Entities;
using redb.Core.Models.Collections;
using redb.Examples.Models;
using redb.Examples.Output;
namespace redb.Examples.Examples;
///
/// Tree statistics via TreeCollection.
/// TreeCollection.GetStats() - node count, depth, leaf count, max width.
///
/// Key method:
/// - **collection.GetStats()** - get tree metrics
///
[ExampleMeta("E112", "Tree - GetStats", "Trees",
ExampleTier.Free, 2, "Tree", "TreeCollection", "GetStats", "Statistics", "Pro", Order = 112)]
public class E112_TreeStats : ExampleBase
{
public override async Task RunAsync(IRedbService redb)
{
// Find root
var roots = await redb.TreeQuery()
.Where(d => d.Code == "CORP")
.Take(1)
.ToListAsync();
if (roots.Count == 0)
return Fail("E112", "Tree - GetStats", ExampleTier.Free, 0, "No tree. Run E088 first.");
var root = (TreeRedbObject)roots[0];
// Load tree and build collection
var sw = Stopwatch.StartNew();
var tree = await redb.LoadTreeAsync(root, maxDepth: 5);
// Build TreeCollection for stats
var collection = new TreeCollection();
AddToCollection(collection, tree);
var stats = collection.GetStats();
sw.Stop();
return Ok("E112", "Tree - GetStats", ExampleTier.Free, sw.ElapsedMilliseconds, collection.Count,
[$"Stats: {stats}", $"Collection count: {collection.Count}"]);
}
private static void AddToCollection(TreeCollection collection, ITreeRedbObject node)
{
collection.Add(node);
foreach (var child in node.Children.OfType>())
AddToCollection(collection, child);
}
}