ASP.Net应用递归算法案例
程序员文章站
2022-10-25 13:03:46
案例需求:动态将一个公司各个部门按照部门顺序排列,在页面动态生成列表,并且子级部门需要比父级部门缩进20px。
页面代码:
:butto...
案例需求:动态将一个公司各个部门按照部门顺序排列,在页面动态生成列表,并且子级部门需要比父级部门缩进20px。
页面代码:
:button id="btncreate" onclick="btncreate_click" runat="server" text="生成">
后台代码:
1、
public class department { public department(int id, string name, int parentid) { this.id = id; this.name = name; this.parentid = parentid; } public int id { get; set; } public string name { get; set; } public int parentid { get; set; } }
2、
list listtc = new list(); public void loaddata() { listtc.add(new department(1, "财务部", 2)); listtc.add(new department(2, "公司总部", 0)); listtc.add(new department(3, "财务组1", 1)); listtc.add(new department(4, "财务组2", 1)); listtc.add(new department(5, "研发部", 2)); listtc.add(new department(6, "研发组1", 5)); listtc.add(new department(7, "研发组2", 5)); listtc.add(new department(8, "研发组3", 5)); listtc.add(new department(9, "业务部", 2)); listtc.add(new department(10, "业务组1", 9)); listtc.add(new department(11, "业务组2", 9)); listtc.add(new department(12, "业务组3", 9)); listtc.add(new department(13,"研发组1第一小组",6)); listtc.add(new department(14, "业务组1第一小组", 10)); listtc.add(new department(15, "研发组1第二小组", 6)); listtc.add(new department(16, "研发组1第二小组1", 15)); listtc.add(new department(17, "研发组1第二小组2", 15)); }
3、
list templist = new list(); public list sort(int parentid) { var tclist = getlisttc(parentid); if (templist.count < listtc.count) { if (tclist.count > 0) { foreach (var tc in tclist) { if (!templist.contains(tc)) { templist.add(tc); return sort(tc.id); } } var t = gettc(parentid); return sort(t.parentid); } else { var tc = gettc(parentid); return sort(tc.parentid); } } else { return templist; } }
4、
public int getlevel(department tc,int level) { var t = listtc.find(o => o.id == tc.parentid); if (t!=null) { level++; return getlevel(t,level); } return level; } public list getlisttc(int parentid) { var list = listtc.findall(o =>o.parentid == parentid); return list; } public department gettc(int id) { var tc = listtc.find(o => o.id == id); return tc; } public string inithtml(int level, string name) { string html = string.empty; html += "
public string createhtml() { var list = sort(0); string strhtml = string.empty; foreach (var tc in list) { int lev = getlevel(tc, 0); strhtml += inithtml(lev, tc.name); } return strhtml; }
6、
protected void btncreate_click(object sender, eventargs e) { loaddata(); this.literal1.text = createhtml(); }
思路:先将数据排序好,根据当前单位的级别数生成li.
页面效果图:
上一篇: android圆角ImageView的几种实现方式
下一篇: 北京徐悲鸿纪念馆