方法一:
//取出第一条
var first = allMenuList.Where(e => e.ParentId == 0).ToList();
//Foreach递归
allMenuList.ForEach(e => e.ChildrenItem = allMenuList.Where(a => a.ParentId == e.Id).ToList());
return first;
方法二:
var first = allMenuList.Where(e => e.ParentId == 0).ToList();
Recursive(first,allMenuList);
private void Recursive(List<MenuListModel> currentMenuList, List<MenuListModel> allMenuList)
{
if (currentMenuList == null || currentMenuList.Count == 0)
{
return;
}
foreach (var item in currentMenuList)
{
item.ChildrenItem = allMenuList.Where(e => e.ParentId == item.Id).ToList();
Recursive(item.ChildrenItem, allMenuList);
};
}
递归会逐层逐层查下去,查到最末节点(第n个节点)时没有数据会原路返回,回到(n-1)个节点,继续查找,如果没有则继续回到(n-2)个节点,一直到第一个节点。