/// <summary>
/// 递归创建小程序类目树
/// </summary>
public List<MiniCategorysTree> BuildMenuTree(MiniCategorysTree node)
{
//条件:item.parent_category_id == node.CategoryId
List<MiniCategorysTree> childrenCategorys = MiniCateGoryList.Where(item => item.parent_category_id == node.CategoryId)
.Select(item => new MiniCategorysTree()
{
Name = item.category_name,
CategoryId = item.category_id,
HasChild = item.has_child,
NeedLicense = item?.need_license,
NeedOutDoorPic = item?.need_out_door_pic,
NeedSpecialLicense = item?.need_special_license,
})
.ToList();
node.ChildrenCategorys = childrenCategorys;
for (int i = 0; i < childrenCategorys.Count; i++)
{
//递归调用创建子节点
if (childrenCategorys[i].HasChild == true)
childrenCategorys[i].ChildrenCategorys = BuildMenuTree(childrenCategorys[i]);
}
return childrenCategorys;
}
在需要用到的地方调用:
MiniCategorysTree nodeRoot = new MiniCategorysTree()
{
Name = "根节点",
CategoryId = "0",
HasChild = true,
NeedLicense = false,
NeedOutDoorPic = false,
NeedSpecialLicense = false,
};
List<MiniCategorysTree> miniCategorysTree = AppService.BuildMenuTree(nodeRoot);
miniCategorysTree
的 结果:
linq 递归
public void init(){
var q=from c in dbs.T_ROLE
select c;
b=q.ToList().AsQueryable();
}
List result= new List ();
List parents= new List ();
IQueryable b;
public void getChilds(int pid)
{
var q = from c in b
where c.T_ROLE_PID == pid
select c;
if (q.Count() > 0)
{
List li = q.ToList();
foreach(db.T_ROLE t in li){
result.Add(t);
getChilds(t.T_ROLE_ID);
}
}
}
public void getParent(int id)
{
var q = from c in b
where c.T_ROLE_ID == id
select c;
if (q.Count() > 0)
{
List li = q.ToList();
foreach(db.T_ROLE t in li)
{
result.Add(t);
getChilds(t.T_ROLE_PID);
}
}
}
这里关键语句为 AsQueryable()
,这样将数据库表变成内存数据表。从而对其进行任意的操作