您的位置:首页 > 产品设计 > UI/UE

EasyUITree实现树形结构Json串

2016-06-15 09:07 351 查看


// 方法一

// 此方法可多级部门使用

public string Bingztree()

{

string where = "";

List<Dept> deptList = DeptService.GetInstance().Select("SelectDept", where).ToList();

StringBuilder sb = new StringBuilder();

string departmentTree = null;

foreach (Dept d in deptList)

{

if (Convert.ToInt32(d.ParentId) == 0)

{

string temp = null;

temp = "\"id\":" + d.DetpId + ",\"text\":\"" + d.DeptName + "\",";

string child = FindChild(Convert.ToInt32(d.DetpId), deptList);

if (child != null)

{

temp += child;

departmentTree = "[{" + temp + "}]";

sb.Append(departmentTree);

}

}

}

string finalTree = sb.ToString();

finalTree = finalTree.Replace("][",",");

return finalTree;

}

private string FindChild(int id, List<Dept> deptList)

{

bool flag = false;

string departmentChild = null;

foreach (Dept d in deptList)

{

string anotherChild = null;

if (Convert.ToInt32(d.ParentId) == id)//寻找到子节点

{

anotherChild = "\"id\":" + d.DetpId + ",\"text\":\"" + d.DeptName + "\",";

string child = FindChild(Convert.ToInt32(d.DetpId), deptList);

if (child != null)

{

anotherChild = anotherChild + child;

}

if (anotherChild[anotherChild.Length - 1] == ',')

{

anotherChild = anotherChild.Remove(anotherChild.Length - 1);

}

anotherChild = "{" + anotherChild + "}";

departmentChild += anotherChild + ",";

}

else

{

flag = false;

}

}

if (departmentChild != null)

{

departmentChild = departmentChild.Remove(departmentChild.Length - 1);

departmentChild = "\"children\":[" + departmentChild + "]";

}

return departmentChild;

}

/// 方法二

/// 备注:此方法仅限两级部门使用

/// <summary>

/// 查询出核实单位,返回json格式

/// </summary>

/// <returns></returns>

public string Bingztree()

{

string where = "";

IList<Dept> deptList = DeptService.GetInstance().Select("SelectDept", where);

StringBuilder sb = new StringBuilder();

sb.Append("[");

List<object> list = new List<object>();

for (int i = 0; i < deptList.Count; i++)

{

list.Add(deptList[i].ParentId);

}

for (int i = 0; i < deptList.Count; i++)

{

if ((int)deptList[i].ParentId == 0)

{

sb.Append("{");

sb.Append(" \"id\": \"" + deptList[i].DetpId + "\",\"text\": \"" + deptList[i].DeptName + "\"");

if (list.Contains(deptList[i].DetpId))

{

sb.Append(",\"children\":[{");

for (int j = 0; j < deptList.Count; j++)

{

if ((int)deptList[j].ParentId == (int)deptList[i].DetpId)

{

sb.Append("\"id\": \"" + deptList[j].DetpId + "\",\"text\": \"" + deptList[j].DeptName + "\"},{");

}

}

sb.Append("]},");

}

else if ((int)deptList[i].ParentId == 0 && !list.Contains(deptList[i].DetpId))

{

sb.Append("},");

}

}

}

string str1 = sb.ToString().Substring(0, sb.Length - 1) + "]";

str1 = str1.Replace("},{]}", "}]}");

return str1;

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: