本文主要是介绍C#匿名委托递归,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
方式一:
var channelNewList = new List<ChannelView>();Action<ChannelView, List<ChannelView>> func = null;func = (q, list) =>{if (q.ChildList != null && q.ChildList.Count > 0){list.AddRange(q.ChildList);//q.ChildList.Clear();foreach (var item in q.ChildList){func(item, list);}}};foreach (var item in channel){channelNewList.Add(item);func(item, channelNewList);}
方式二:
加载的数据生成到select下拉框中,按照层级顺序显示
/// <summary>/// 读取部门层级,全部部门都显示在同一级,父级后面跟子集,每个节点有Level层级int数据,/// </summary>/// <returns></returns>/// <remarks>/// 创建时间:2021-1-13 10:54:31/// </remarks>public async Task<List<DepartmentView>> GetListByTreeAsync(int? state){//读取部门List<Department> list2 = null;if (state.HasValue){list2 = await departmentDAL.GetListAsync(x => x.D_status == state);}else{//加载所有部门数据list2 = await departmentDAL.GetAllListAsync();}// 排除父id和本身id相同导致的递归异常list2 = list2.Where(x => x.Id != x.Parent_id).ToList();List<DepartmentView> cList = list2.Select(x => new DepartmentView() { Id = x.Id, Department_name = x.Department_name, Parent_id = x.Parent_id, Sno = x.Sno,D_status=x.D_status}).ToList();//输出列表,全部部门都显示在同一级目录,子集紧跟父级后面List<DepartmentView> dList = new List<DepartmentView>();Action<DepartmentView, List<DepartmentView>> func = null;func = (q, list) =>{if (q.Childs != null && q.Childs.Count > 0){foreach (var item in q.Childs){item.Level = q.Level + 1;item.Childs = cList.Where(x => x.Parent_id == item.Id).OrderBy(x => x.Sno).ToList();list.Add(item);if (item.Childs != null && q.Childs.Count > 0){func(item, list);}} }};//读取一级部门var list1 = cList.Where(x=>string.IsNullOrWhiteSpace(x.Parent_id)).ToList();for (int i = 0; i < list1.Count; i++){var item = list1[i];item.Childs = cList.Where(x => x.Parent_id == item.Id).OrderBy(x=>x.Sno).ToList();if (string.IsNullOrWhiteSpace(item.Parent_id)){item.Level = 1;dList.Add(item);}func(item, dList);}foreach (var item in dList){item.Childs?.Clear();}return dList;}
public class DepartmentView {/// <summary>/// guid主键/// </summary>[Key]public string Id { set; get; }/// <summary>/// 部门名称/// </summary>public string Department_name { get; set; }/// <summary>/// 父级id/// </summary>public string Parent_id { get; set; }/// <summary>/// 是否启用,1=启用,0=禁用/// </summary>public byte? D_status { get; set; }/// <summary>/// 排序/// </summary>public int Sno { get; set; }/// <summary>/// 当前等级/// </summary>public uint Level { get; set; }/// <summary>/// 子集部门/// </summary>public List<DepartmentView> Childs { get; set; }}
执行结果:
翰林院
*学士院
**学士甲舍
**学士乙舍
**学士丙舍
*中书舍人院
门下省
*礼部
*吏部
*工部
*刑部
*户部
*兵部
这篇关于C#匿名委托递归的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!