Path: redb/redb.Core/Models/Collections/TreeCollection.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.Core/Models/Collections/TreeCollection.cs ---- using System; using System.Collections.Generic; using System.Collections; using System.Linq; using redb.Core.Utils; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; namespace redb.Core.Models.Collections { /// /// Specialized collection for working with tree-structured objects /// Automatically builds hierarchy when adding nodes /// Supports polymorphic trees (objects of different schemes in one tree) /// public class TreeCollection : IEnumerable { private readonly Dictionary _nodesById = new(); private readonly List _roots = new(); private readonly List _orphans = new(); // Nodes whose parents haven't been added yet /// /// Gets count of nodes in collection /// public int Count => _nodesById.Count; /// /// Gets all root nodes (without parents) /// public IEnumerable Roots => _roots.AsReadOnly(); /// /// Gets all leaf nodes (without children) /// public IEnumerable Leaves => _nodesById.Values.Where(n => n.IsLeaf); /// /// Gets orphan nodes (whose parents haven't been added to collection) /// public IEnumerable Orphans => _orphans.AsReadOnly(); /// /// Adds node to collection and automatically builds hierarchy /// /// Node to add public void Add(ITreeRedbObject node) { if (node == null) throw new ArgumentNullException(nameof(node)); // Check if this node hasn't been added already if (_nodesById.ContainsKey(node.Id)) { throw new InvalidOperationException($"Node with ID {node.Id} already added to collection"); } _nodesById[node.Id] = node; // If this is a root node if (node.IsRoot) { _roots.Add(node); } else { // Look for parent if (_nodesById.TryGetValue(node.ParentId!.Value, out var parent)) { // Parent found - establish connections ConnectChild(parent, node); // Remove from orphans list if it was there _orphans.Remove(node); } else { // Parent not found - add to orphans list _orphans.Add(node); } } // Check if this node became parent for any orphans CheckForOrphansToAdopt(node); } /// /// Adds range of nodes /// /// Nodes to add public void AddRange(IEnumerable nodes) { foreach (var node in nodes) { Add(node); } } /// /// Finds node by ID /// /// Node ID /// Found node or null public ITreeRedbObject? FindById(long id) { return _nodesById.GetValueOrDefault(id); } /// /// Finds nodes by predicate /// /// Search condition /// Collection of found nodes public IEnumerable FindNodes(Func predicate) { return _nodesById.Values.Where(predicate); } /// /// Removes node from collection /// /// ID of node to remove /// true if node was removed public bool Remove(long id) { if (!_nodesById.TryGetValue(id, out var node)) return false; // Remove node from structure if (node.IsRoot) { _roots.Remove(node); } else if (node.Parent != null) { node.Parent.Children.Remove(node); } // Make children orphans foreach (var child in node.Children.ToList()) { child.Parent = null; _orphans.Add(child); } // Remove from all collections _nodesById.Remove(id); _orphans.Remove(node); return true; } /// /// Clears collection /// public void Clear() { _nodesById.Clear(); _roots.Clear(); _orphans.Clear(); } /// /// Checks if node with specified ID is contained /// /// Node ID /// true if node is contained in collection public bool Contains(long id) { return _nodesById.ContainsKey(id); } /// /// Gets collection statistics /// /// Statistics object public TreeCollectionStats GetStats() { var allNodes = _nodesById.Values; var maxDepth = _roots.Any() ? _roots.Max(root => root.MaxDepth) : 0; var totalNodes = allNodes.Count(); return new TreeCollectionStats { TotalNodes = totalNodes, RootNodes = _roots.Count, LeafNodes = Leaves.Count(), OrphanNodes = _orphans.Count, MaxDepth = maxDepth, AverageChildrenPerNode = totalNodes > 0 ? allNodes.Average(n => n.Children.Count) : 0 }; } /// /// Gets flattened list of all nodes with level indication /// /// List of (node, level) pairs public IEnumerable<(ITreeRedbObject Node, int Level)> GetFlattenedWithLevels() { var result = new List<(ITreeRedbObject, int)>(); foreach (var root in _roots) { foreach (var node in root.GetSubtree()) { var level = node.Level; result.Add((node, level)); } } // Add orphans with level -1 (undefined) foreach (var orphan in _orphans) { result.Add((orphan, -1)); } return result; } /// /// Validates tree integrity /// /// List of found issues public IEnumerable ValidateIntegrity() { var issues = new List(); foreach (var node in _nodesById.Values) { // Check that ParentId matches Parent if (node.ParentId.HasValue) { if (node.Parent == null) { issues.Add($"Node {node.Id} has ParentId={node.ParentId}, but Parent=null"); } else if (node.Parent.Id != node.ParentId.Value) { issues.Add($"Node {node.Id}: ParentId={node.ParentId} doesn't match Parent.Id={node.Parent.Id}"); } } // Check that all children have correct back reference foreach (var child in node.Children) { if (child.Parent != node) { issues.Add($"Child node {child.Id} doesn't reference parent {node.Id}"); } if (child.ParentId != node.Id) { issues.Add($"Child node {child.Id}: ParentId={child.ParentId} doesn't match parent {node.Id}"); } } } return issues; } #region Private Methods /// /// Establishes parent-child relationship /// private void ConnectChild(ITreeRedbObject parent, ITreeRedbObject child) { child.Parent = parent; if (!parent.Children.Contains(child)) { parent.Children.Add(child); } } /// /// Checks if node became parent for any orphans /// private void CheckForOrphansToAdopt(ITreeRedbObject potentialParent) { var childrenToAdopt = _orphans.Where(orphan => orphan.ParentId == potentialParent.Id).ToList(); foreach (var child in childrenToAdopt) { ConnectChild(potentialParent, child); _orphans.Remove(child); } } #endregion #region IEnumerable Implementation public IEnumerator GetEnumerator() { return _nodesById.Values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } /// /// Typed version of collection for backward compatibility /// Wrapper over polymorphic TreeCollection with type safety /// /// Type of object properties public class TreeCollection : IEnumerable> where TProps : class, new() { private readonly TreeCollection _baseCollection = new(); /// /// Gets count of nodes in collection /// public int Count => _baseCollection.Count; /// /// Gets all root nodes (without parents) /// public IEnumerable> Roots => _baseCollection.Roots.Cast>(); /// /// Gets all leaf nodes (without children) /// public IEnumerable> Leaves => _baseCollection.Leaves.Cast>(); /// /// Gets orphan nodes (whose parents haven't been added to collection) /// public IEnumerable> Orphans => _baseCollection.Orphans.Cast>(); /// /// Adds typed node to collection /// public void Add(ITreeRedbObject node) { _baseCollection.Add(node); } /// /// Adds range of typed nodes /// public void AddRange(IEnumerable> nodes) { _baseCollection.AddRange(nodes.Cast()); } /// /// Finds typed node by ID /// public ITreeRedbObject? FindById(long id) { return _baseCollection.FindById(id) as ITreeRedbObject; } /// /// Finds typed nodes by predicate /// public IEnumerable> FindNodes(Func, bool> predicate) { return _baseCollection.FindNodes(node => node is ITreeRedbObject typed && predicate(typed)) .Cast>(); } /// /// Removes node from collection /// public bool Remove(long id) => _baseCollection.Remove(id); /// /// Clears collection /// public void Clear() => _baseCollection.Clear(); /// /// Checks if node with specified ID is contained /// public bool Contains(long id) => _baseCollection.Contains(id); /// /// Gets collection statistics /// public TreeCollectionStats GetStats() => _baseCollection.GetStats(); /// /// Gets flattened list of all typed nodes with level indication /// public IEnumerable<(ITreeRedbObject Node, int Level)> GetFlattenedWithLevels() { return _baseCollection.GetFlattenedWithLevels() .Where(item => item.Node is ITreeRedbObject) .Select(item => ((ITreeRedbObject)item.Node, item.Level)); } /// /// Validates tree integrity /// public IEnumerable ValidateIntegrity() => _baseCollection.ValidateIntegrity(); public IEnumerator> GetEnumerator() { return _baseCollection.Cast>().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } /// /// Tree collection statistics /// public class TreeCollectionStats { public int TotalNodes { get; set; } public int RootNodes { get; set; } public int LeafNodes { get; set; } public int OrphanNodes { get; set; } public int MaxDepth { get; set; } public double AverageChildrenPerNode { get; set; } public override string ToString() { return $"Nodes: {TotalNodes}, Roots: {RootNodes}, Leaves: {LeafNodes}, Orphans: {OrphanNodes}, MaxDepth: {MaxDepth}, AvgChildren: {AverageChildrenPerNode:F1}"; } } }