如何使用Dictionary填充treeview

时间:2014-03-26 07:06:56

标签: c# dictionary treeview

您好我正在使用字典来填充我的树视图...

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()背后的代码中是用字典vaules填充我的树视图的函数..我知道下面的代码不完整..我只是成功显示经理和会计,我不知道如何填充其子节点..

我已经尝试过这么多但是无法做到..我坚持了一周就好了..请帮忙

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);
                        }
                    }              
               }

        }

1 个答案:

答案 0 :(得分:0)

我认为您正在寻找在给定层次结构的情况下构建树视图的逻辑。

值存在于employees参数中。构建Id->Employee map,遍历值,找到parent并将employee添加为parent&#39; s 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
}