且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

删除第 N 层嵌套集合中的项目

更新时间:2023-02-13 13:32:20

我会通过对我的设计做一个小的改变来解决这个问题(假设你问题中的代码片段是一个类的伪代码):

I would deal with this by making a small change to my design (assuming the snippet in your question is pseudocode for a class):

TreeNode
{
    string name;
    TreeNode Parent;
    ObservableCollection<TreeNode> Children;

    public void Delete()
    {
        Parent.Children.Remove(this);
    }
}

这让您在操作对象图时维护一个额外的引用需要做更多的工作,但在执行删除等操作时会为您节省大量精力和代码,如您所见.

This makes a little bit more work for you maintaining an extra reference when manipulating your object graph, but saves you a lot of effort and code when doing things like deletes as you can see above.

你还没有展示你是如何构造 TreeNode 的,但我会为构造函数的子参数创建父节点和集合.

You haven't shown how you're constructing TreeNodes, but I'd make the parent and a collection for the children arguments of the constructor.