现在的位置: 主页 > 新闻中心 > 文章正文

ASP.Net应用递归算法案例

作者:福州市名人视觉形象设计职业培训学校 来源:www.mrssjy.com 发布时间:2017-09-06 13:11:33
ASP.Net应用递归算法案例

案例需求:动态将一个公司各个部门按照部门顺序排列,在页面动态生成列表,并且子级部门需要比父级部门缩进20px。

页面代码:


后台代码:

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 += "

  • 5、 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.

    页面效果图:

    企业建站2800元起,携手武汉肥猫科技,做一个有见地的颜值派!更多优惠请戳:武汉做网站 https://www.feimao666.com

    上一篇:武汉肥猫科技|有颜值又有见地的网站总是经久不衰 下一篇:最后一页