using System.Collections;
using System.Collections.Generic;
public static void Main()
Console.WriteLine("Hello World");
var categories = new List<Category>(){
new(){ Id = 1 , Name="Sports", ParentId = 0},
new(){ Id = 2 , Name="Balls", ParentId = 1},
new(){ Id = 3 , Name="Shoes", ParentId = 1},
new(){ Id = 4 , Name="Electronics", ParentId = 0},
new(){ Id = 5 , Name="Cameras", ParentId = 4},
new(){ Id = 6 , Name="Lenses", ParentId = 5},
new(){ Id = 7 , Name="Tripod", ParentId = 5},
new(){ Id = 8 , Name="Computers", ParentId = 4},
new(){ Id = 9 , Name="Laptops", ParentId = 8},
new(){ Id = 10, Name="Empty", ParentId = 0}
var root = GenericHelpers.GenerateTree(categories, c=> c.Id, c=> c.ParentId, (c, newItems) => c.Children = newItems);
static void Test(IEnumerable<Category> categories, int deep = 0)
foreach (var c in categories)
Console.WriteLine(new String('\t', deep) + c.Name);
Test(c.Children, deep + 1);
public IEnumerable<Category> Children;
internal static class GenericHelpers
public static IEnumerable<T> GenerateTree<T, K>(
this IEnumerable<T> collection,
Func<T, K> parent_id_selector,
Action<T, IEnumerable<T>> childrenApplier,
foreach (var c in collection.Where(c => EqualityComparer<K>.Default.Equals(parent_id_selector(c), root_id)))
var children = collection.GenerateTree<T,K>(id_selector, parent_id_selector, childrenApplier, id_selector(c));
childrenApplier(c, children);