如何使用字典填充树视图
本文关键字:视图 填充 字典 何使用 | 更新日期: 2023-09-27 17:53:18
嗨,我正在使用字典填充我的树视图…
Dictionary<int, Dictionary<string, int>> management = new Dictionary<int, Dictionary<string, int>>();
现在管理有以下值
ID Name Parent
1 Manager 0
2 Accountant 0
3 Assistant Manager 1
4 Branch Manager 1
5 Employee1 3
6 Employee3 3
7 Employee2 4
8 Accountant1 2
9 Accountant2 2
在DispalyTree()后面的代码是用字典值填充我的treeview的函数。我知道下面的代码是不完整的…我刚刚成功地显示了Manager和accounting,我不知道如何填充它的子节点。
我已经试了那么多,但不能……我被这个困了一个星期…请帮助
public void DisplayTree()
{
TreeNode parentnode = new TreeNode();
TreeBL l_bltree = new TreeBL();
Dictionary<int, Dictionary<string, int>> manage = new Dictionary<int, Dictionary<string, int>>();
manage = l_bltree.ChildTree();
foreach (var kvp in manage)
{
var innerDict = kvp.Value;
foreach (var innerKvp in innerDict)
{
parentnode = new TreeNode(innerKvp.Key);
if (innerKvp.Value == 0)
{
treeview.Nodes.Add(parentnode);
}
}
}
}
我认为您正在寻找逻辑来构建给定层次结构的树视图。
这些值存在于employees
参数中。构建Id->Employee map
,遍历值,找到parent
并将employee
添加为parent
的child
。最后,您只需要root
或它的children
。
// quick and dirty class
public class Employee
{
public int Id;
public string Name;
public int ParentId;
public IList<Employee> Children = new List<Employee>();
public override int GetHashCode()
{
return Id;
}
public override bool Equals(object obj)
{
Employee that;
return
obj != null
&& (that = obj as Employee) != null
&& Id == that.Id;
}
}
// O(n) time, O(n) space for hashmap
public Employee BuildTreeView(IEnumerable<Employee> employees)
{
var rootEmployee = new Employee() { Id = 0 };
var IdToEmployeeMap = employees.ToDictionary(e => e.Id);
IdToEmployeeMap[0] = rootEmployee;
foreach (var employee in employees)
{
var parentEmployee = IdToEmployeeMap[employee.ParentId];
parentEmployee.Children.Add(employee);
}
return rootEmployee; // or return rootEmployee.Children if interested in children
}