I've further elaborated the idea above, using an extension method:
// Base interfaces for a node
public interface INode
where T : INode // A child is the same class as the parent
{
Guid Id { get; set; }
List Children { get; set; }
}
// Static class containing Extension Methods
public static class NodeExtensions
{
// Recursively removes a node by its id
public static void Remove(this INode node, Guid id)
where T : INode
{
// List that will contains the nodes to be removed
// Can't remove nodes directly in the foreach loop
// (will throw "Collection was modified; enumeration operation may not execute.")
List toRemove = new List();
if (node.Children == null)
return; // No childrens, exit
foreach (var child in node.Children)
{
if (child.Id == id)
toRemove.Add(child); // The node has to be removed
else
child.Remove(id); // Recursion here
}
// Removes all found nodes
foreach (var child in toRemove)
node.Children.Remove(child);
}
}