删除第 N 层嵌套集合中的项目 [英] Delete item in nested collections of Nth level

查看:35
本文介绍了删除第 N 层嵌套集合中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试删除树结构对象内的项目时遇到问题.

I'm having trouble trying to delete a item inside a tree structured object.

我的对象如下

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

我想如果我递归处理树并找到我的节点并删除它,但我遇到了麻烦.

I thought if I recursively process through the tree and find my node and delete it but I ran into trouble.

我做了一些类似

更新:

DeleteNode(ObservableCollection<TreeNode> children, TreeNode nodetodelete)
{
    if(children.remove(nodetodelete))
    {
        return;
    }
    else
    {
        foreach(var child in children)
        {
            DeleteNode(child, nodetodelete);
        }
    }
}

我在编写代码时意识到,在迭代可能被更改的集合时,我最终会遇到操作异常.
我可以构建一个巨大的 for 循环更改,因为我确切地知道最大深度长度(我为占位符所做的),但这看起来真的很糟糕....
任何人都可以指出我更好的总体方向.我有点想知道我的数据结构是否是造成这种情况的原因.

I realize while I was writing the code that I would eventually run into manipulation exception while iterating through a collection that has a chance of being changed.
I could build a giant change of for loops since I know exactly the max deep length(which I did for a place holder) but that seems really bad. . . .
Can anyone point me in a better general direction. I kind of wonder if my data structure is the cause of this.

更新:

这看起来很糟糕,有点代码味道,但我得到了工作"的递归当我找到我的节点时抛出异常.

This will look awful and kinda of code smell but I got the recursion to "work" by throw a exception when I find my node.

DeleteNode(children, nodetodelete)
    {
        if(children.remove(nodetodelete)
        {
            throw FoundException();
        }
        else
        {
            foreach(var child in children)
            {
                DeleteNode(child, nodetodelete)
            }
        }
    }

有没有其他方法可以打破递归.

Is there any other way of breaking out of a recursion.

推荐答案

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

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.

这篇关于删除第 N 层嵌套集合中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆