第一种
直接实体添加Children
实体类 public class DepartmentItem { /// <summary> /// 部门Id /// </summary> public int ID { get; set; } /// <summary> /// 部门名称 /// </summary> public string DepartmentName { get; set; } /// <summary> /// 上级部门Id /// </summary> public int? ParentSysDepartmentId { get; set; } /// <summary> /// 企业Id /// </summary> public int SysEnterpriseId { get; set; } /// <summary> /// 部门GUID /// </summary> public string DepartmentGUID { get; set; }
//下级 public IEnumerable<DepartmentItem> Children { get; set; } }
方法 private List<DepartmentItem> GetChildren(IEnumerable<DepartmentItem> dt, int? ID) { List<DepartmentItem> nodeList = new List<DepartmentItem>(); var children = dt.Where(q => q.ParentSysDepartmentId == ID); foreach (var dr in children) { DepartmentItem node = new DepartmentItem(); node.ID = dr.ID; node.DepartmentGUID = dr.DepartmentGUID; node.SysEnterpriseId = CurrentUser.PlatformUser.userEnterInfo.EnterpriseId; node.DepartmentName = dr.DepartmentName; node.ParentSysDepartmentId = dr.ParentSysDepartmentId; node.Children = GetChildren(dt, node.ID); nodeList.Add(node); } return nodeList; }
直接调用 var tt = GetChildren(apire.Data,null);
第二种
依次返回数据 根据RLevel级别判断
/// <summary> /// 行政区域表 /// </summary> public class ProJ_Region :BaseModelInt { /// <summary> /// 上一级id /// </summary> public int ParentID { get; set; } /// <summary> /// 工程项目ID /// </summary> public Guid ProjectID { get; set; } /// <summary> /// 行政区域名 /// </summary> public string RegionName { get; set; } /// <summary> /// 级次 /// </summary> public int RLevel { get; set; } }
/// <summary> /// 获取包含自己的子级 /// </summary> /// <param name="regionid"></param> /// <returns></returns> public IEnumerable<Model.DB.ProJ_Region> GetChildren(int regionid) { if (!_region.Contains(q => q.ID == regionid)) yield break; foreach (var x in _region.Get(q => q.ID == regionid)) yield return x; foreach (var x in _region.Get(q => q.ParentID == regionid)) { foreach (var y in GetChildren(x.ID)) yield return y; } }
var re = GetChildren(RegionID);