Files
Atomx/Atomx.Utils/Extension/TreeExtension.cs
2025-12-30 18:07:41 +08:00

37 lines
1.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Text;
namespace Atomx.Utils.Extension
{
public static class TreeExtension
{
public static List<T> ToTree<T>(this List<T> list, Func<T, string> getId, Func<T, string> getParentId, Action<T, List<T>> setChildren, string rootParentId = "0")
{
var lookup = new Dictionary<string, T>();
var result = new List<T>();
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<T>();
setChildren(parent, children);
children.Add(item);
}
}
return result;
}
}
}