public class BuildTreeExtension
{
public List<T> GetChildList<T>(string parentId, List<T> sourceList, string idFieldName, string sjIdFieldName, string childFieldName)
{
List<T> list = new List<T>();
if (sourceList != null && sourceList.Count > 0)
{
var tempList = new List<T>();
//找到所有子级节点
foreach (var item in sourceList)
{
Type t = item.GetType();
object curParentID = t.GetProperty(sjIdFieldName).GetValue(item, null);
if (curParentID != null && curParentID.ToString() == parentId)
{
tempList.Add(item);
}
}
if (tempList != null && tempList.Count > 0)
{
foreach (var item in tempList)
{
//获取当前子节点的ID值
Type t = item.GetType();
object curID = t.GetProperty(idFieldName).GetValue(item, null);
List<T> itemList = new List<T>();
if (curID != null && !string.IsNullOrEmpty(curID.ToString()))
{
//获取子节点的子节点集合
itemList = GetChildList(curID.ToString(), sourceList, idFieldName, sjIdFieldName, childFieldName);
}
//赋值子节点集合
if (itemList != null && itemList.Count > 0)
{
t.GetProperty(childFieldName)?.SetValue(item, itemList, null);
}
list.Add(item);
}
}
}
return list;
}
}
```
调用方式
```csharp
//最顶级数据
var parentList = source.FindAll(x => string.IsNullOrWhiteSpace(x.sj_id));
var treeExtension = new BuildTreeExtension();
var result = new List<BsptTreeResDto>();
parentList?.ForEach(x =>
{
//构建下级
x.child = treeExtension.GetChildList(x.id, source, nameof(x.id), nameof(x.sj_id), nameof(x.child));
result.Add(x);
});
asp .net core 构建树形结构
于 2023-04-23 10:45:06 首次发布