C# Tree sorting for inserting rows in the correct order

Date: 2023-06-20
public interface ITreeNode
{
	Guid Id { get; }
	Guid? ParentId { get; }
}

public class TreeSorter
{
	public static IEnumerable<T> Sort<T>(IEnumerable<T> allNodes) where T: ITreeNode
	{
		var sortedNodes = new List<T>();
		var visited = new HashSet<Guid>();
		foreach (var node in allNodes)
			Visit(allNodes, node, visited, ref sortedNodes);
		return sortedNodes;
	}

	private static void Visit<T>(IEnumerable<T> allNodes, T node, HashSet<Guid> visited, ref List<T> sortedNodes) where T : ITreeNode
	{
		if (visited.Contains(node.Id)) return;
		visited.Add(node.Id);
		var parentNode = allNodes.FirstOrDefault(n => n.Id == node.ParentId);
		if (parentNode != null)
			Visit(allNodes, parentNode, visited, ref sortedNodes);
		sortedNodes.Add(node);
	}
}
78790cookie-checkC# Tree sorting for inserting rows in the correct order