您可以按 ManagerID 对列表进行排序,假设没有经理的人的 ManagerID = 0,因为重要的是首先添加“顶级”经理,然后从顶部开始添加并搜索父级,如果没有父母然后人是没有经理的“顶级”经理,并将其添加到树视图的根目录。
像这样的东西:
protected void Page_Load(object sender, EventArgs e)
{
List<People> pplList = LoadPeople();
foreach (People person in pplList.OrderBy(pp => pp.ManagerID))
{
IEnumerable<TreeNode> nodes = Extensions.GetItems<TreeNode>(TreeViewPeople.Nodes, item => item.ChildNodes);
TreeNode parent = nodes.FirstOrDefault(nn => nn.Value.Equals(person.ManagerID.ToString()));
TreeNode newNode = new TreeNode(person.Name, person.ID.ToString());
if (parent == null)
TreeViewPeople.Nodes.Add(newNode);
else
parent.ChildNodes.Add(newNode);
}
}
这是将返回所有树节点的 GetItems 方法,取自此处:https ://stackoverflow.com/a/1815600/351383
public static class Extensions
{
public static IEnumerable<T> GetItems<T>(this IEnumerable collection, Func<T, IEnumerable> selector)
{
Stack<IEnumerable<T>> stack = new Stack<IEnumerable<T>>();
stack.Push(collection.OfType<T>());
while (stack.Count > 0)
{
IEnumerable<T> items = stack.Pop();
foreach (var item in items)
{
yield return item;
IEnumerable<T> children = selector(item).OfType<T>();
stack.Push(children);
}
}
}
}