1

我有一个按以下方式设置的列表,我想以相反的顺序搜索和操作(删除项目),但我想不出一个好方法来做到这一点。

目前,该列表是一个Observable Collection,但我可以将其更改为另一种类型。

我可以使用递归搜索列表,但我如何搜索(从孩子开始,然后向上)?

ID、ListOfChildren <>、姓名

例如:

ID: 1, ListOfChildren Count = 2, Name = "Room 1"<br>
--- ID 10, ListOfChildren, Count = 0, Name = "Bed 1.1"<br>
--- ID 11, ListOfChildren, Count = 0, Name = "Bed 1.2"<br>

ID: 2, ListOfChildren Count = 2, Name = "Room 2"<br>
--- ID 12, ListOfChildren, Count = 0, Name = "Bed 2.1"<br>
--- ID 13, ListOfChildren, Count = 0, Name = "Bed 2.2"<br>

ID: 3, ListOfChildren Count = 2, Name = "Room 3"<br>
--- ID 14, ListOfChildren, Count = 0, Name = "Bed 3.1"<br>
--- ID 15, ListOfChildren, Count = 0, Name = "Bed 3.2"<br>

谢谢,比尔

4

1 回答 1

0

您可以执行与按顺序搜索相反的操作,让方法返回是否需要删除子项。将顺序改写为实际上是相反的。或者在子节点中添加对父节点的引用,是的,这会花费额外的内存,这就是为什么您几乎总是必须遍历树的原因。

public class Tree
{
    private static Random rand = new Random();
    public List<Tree> Children = new List<Tree>();

    public Tree Parent;

    public string Name;

    public Tree(Tree parent)
    {
        Parent = parent;
        Name = rand.Next(10000).ToString();
    }

    // Removing without tree traversal.
    public void DeleteParent()
    {
        this.Parent.Parent.Children.Remove(this.Parent);
    }

    public bool Remove(string name)
    {
        for(int i = Children.Count - 1; i >= 0; i--)
        {
            if (Children[i].Remove(name))
            {
                // Use a for-loop with index to remove the child right away.
                Children.Remove(Children[i]);
                // Extra remove handling
                i--;
            }
        }

        // Remove condition.
        return this.Name.Contains(name);
    }
}

发生这种情况有什么关系吗?如果您删除一个父级,它的所有子级都将被内存管理删除。

于 2013-07-28T17:39:47.553 回答