递归
将数据库里具有层级关系的数据查询出来拼接成json字符串。
以部门为例:
(代码_记录)
public string GetDepart()
{
//获取全部集合
List<DepartModel> allModel = new List<DepartModel>();
List<Sys_Department> dt = departmentDal.GetAll().ToList();
for (int i = 0; i < dt.Count; i++)
{
DepartModel model = new DepartModel();
model.id = dt[i].SD_ID;
model.text = dt[i].SD_Name;
model.SD_Sup = dt[i].SD_Sup;
allModel.Add(model);
}
//第一级部门
var topItems = allModel.Where(e => e.SD_Sup == 0).ToList();
List<DepartModel> topModels = new List<DepartModel>();
foreach (var item in topItems)
{
DepartModel topModel = new DepartModel();
topModel.id = item.id;
topModel.text = item.text;
topModel.SD_Sup = item.SD_Sup;
LoopToAppendChildren(allModel, topModel);
topModels.Add(topModel);
}
string json = JsonConvert.SerializeObject(topModels);
return json;
}
public void LoopToAppendChildren(List<DepartModel> allList, DepartModel curItem)
{
var subItems = allList.Where(ee => ee.SD_Sup == curItem.id).ToList();
curItem.children = new List<DepartModel>();
curItem.children.AddRange(subItems);
foreach (var subItem in subItems)
{
LoopToAppendChildren(allList, subItem);
}
}
public class DepartModel
{
public int id;
public string text;
public int SD_Sup;
public List<DepartModel> children;
}