using System; using System.Collections.Generic; using System.Text; namespace Atomx.Utils.Extension { public static class TreeExtension { public static List ToTree(this List list, Func getId, Func getParentId, Action> setChildren, string rootParentId = "0") { var lookup = new Dictionary(); var result = new List(); foreach (var item in list) { var id = getId(item); lookup[id] = item; } foreach (var item in list) { var parentId = getParentId(item); if (parentId == rootParentId || !lookup.ContainsKey(parentId)) { result.Add(item); } else { var parent = lookup[parentId]; var children = new List(); setChildren(parent, children); children.Add(item); } } return result; } } }