注意原始数据不要是IEnumable
方法1
//前提,包含父级关联字段,比如ParentId和Id
//原始数组
var list = new List<dynamic>();
//顶层数组
var rootMenus = new List<SysMenuDto>();
foreach (var item in list)
{
var parent = list.FirstOrDefault(x => x.Id == item.ParentId);
if (parent.IsNull())
{
rootMenus.Add(item);
continue;
}
parent!.Children.Add(item);
}
return rootMenus;
方法2
var list = menus.Select(x =>
{
var item = x.Adapt<SysMenuDto>();
item.Meta = x.Adapt<SysMenuMetaDto>();
return item;
}).ToList();
var menuDictionary = list.ToDictionary(menu => menu.Id);
var rootMenus = new List<SysMenuDto>();
foreach (var menu in list)
{
if (menu.ParentId == 0)
{
rootMenus.Add(menu);
}
else if (menuDictionary.TryGetValue(menu.ParentId, out SysMenuDto parentMenu))
{
parentMenu.Children.Add(menu);
}
}
return rootMenus;