[英]Reverse search a lists of lists
I have a list set up in the following manner that I would like to search and manipulate (delete items) in reverse order, but I can't figure out a good way to do this. 我以下面的方式设置了一个列表,希望以相反的顺序进行搜索和操作(删除项目),但是我找不到解决此问题的好方法。
Currently, the list is an Observable Collection
, but I can change it to another type. 当前,列表是
Observable Collection
,但是我可以将其更改为其他类型。
I am able to search down the list using recursion, but how do I search up (starting with the children and working my way up)? 我可以使用递归向下搜索列表,但是如何向上搜索(从子级开始并逐步向上)?
ID, ListOfChildren <>, Name ID,ListOfChildren <>,名称
For example: 例如:
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>
Thanks, Bill 谢谢,比尔
You could do the opposite of an in-order search, have the method return wether the child needs to be removed. 您可以执行有序搜索的相反操作,让该方法返回是否需要删除子项。 Rewrote the order to actually be reverse.
将命令改写为实际上是相反的。 Or add a reference to the parent in the child, yes that costs extra memory, which is why you almost always have to traverse the tree.
或者在孩子中添加对父对象的引用,是的,这会占用额外的内存,这就是为什么您几乎总是必须遍历树。
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);
}
}
Does it matter what order this happens? 发生什么顺序有关系吗? If you delete a parent all it's children will be removed by the memory management.
如果删除父级,则其所有子级将被内存管理器删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.