c# - 如何获取在 TreeView 控件中选择的所有父节点(直到根节点)?

标签 c# asp.net treeview hierarchy

如果我有一个 TreeView (myTreeview),我如何获得所选节点的所有父节点(父节点、父节点的父节点等)的列表?

最佳答案

我建议您创建一组自己的树助手,例如,下一个是针对您的问题:

    public static class TreeHelpers
    {
        public static IEnumerable<TItem> GetAncestors<TItem>(TItem item, Func<TItem, TItem> getParentFunc)
        {
            if (getParentFunc == null)
            {
                throw new ArgumentNullException("getParentFunc");
            }
            if (ReferenceEquals(item, null)) yield break;
            for (TItem curItem = getParentFunc(item); !ReferenceEquals(curItem, null); curItem = getParentFunc(curItem))
            {
                yield return curItem;
            }
        }

        //TODO: Add other methods, for example for 'prefix' children recurence enumeration
    }

和用法示例(在您的上下文中):

        IList<TreeNode> ancestorList = TreeHelpers.GetAncestors(node, x => x.Parent).ToList();

为什么这比使用 list<>.Add() 更好? - 因为我们可以使用惰性 LINQ 函数,例如 .FirstOrDefault(x => ...)

附言要将“当前”项目包含到结果可枚举中,请使用 TItem curItem = item,而不是 TItem curItem = getParentFunc(item)

关于c# - 如何获取在 TreeView 控件中选择的所有父节点(直到根节点)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8120746/

相关文章:

c# - 虚拟化不改变新可见项目的属性

c# - System.Windows.Forms.Screen.DeviceName 在 Windows XP 上产生垃圾

css - 将一个元素的 Css Intellisense 包含在另一个元素中

asp.net - 使用内联标记初始化用户控件属性值

c# - ObjectContext 实例已被释放

c# - C#Nest Elasticsearch:如何搜索多个参数

delphi - 在delphi中取消选择 TreeView 的元素

google-app-engine - 如何在谷歌搜索中使谷歌网页树状 View ?

asp.net - 无法获取IIS提取目录

delphi - 如何使 TTreeView 在禁用时不突出显示所有节点?