简体   繁体   English

递归搜索类别及其子级

[英]Recursive Searching Category and Their Children

I have the following class: 我有以下课程:

public class Category {
    public string Name { get; set; }
    public Category Parent { get; set; }
    public string Url { get; set; }
    public List<Category> Children { get; set; }
}

Now given an instance of a Category and url. 现在给出一个Category和url的实例。 I wish to get the Category where the url matches the category or any of it's children (or their children etc). 我希望获得URL匹配类别或其任何子代(或他们的子代等)的类别。

Therefore my function would have the following signature: 因此,我的函数将具有以下签名:

public Category FindCategory(Category category, string url);

I know recursion is the way to go and i have managed to come up with a solution. 我知道递归是要走的路,我已经设法提出了解决方案。 However i've definitely seen it done better but i can't find where. 但是我肯定已经看到它做得更好,但是我找不到地方。 I'd appreciate it if someone could show me the easiest and cleanest way to achieve this. 如果有人可以向我展示最简单,最干净的方法,我将不胜感激。

Thanks 谢谢

In terms of recursion the answer is pretty straight forward. 在递归方面,答案很简单。 I would prefer the Try pattern over a null return though. 我更喜欢Try模式而不是null返回。

bool TryFind(string url, Category current, out Category found) {
  if (category.Url == url) {
    found = current;
    return true;
  }

  foreach (var child in current.Children) {
    if (TryFind(url, child, out found)) {
      return true;
    }
  }

  found = null;
  return false;
}

Your question mentioned you'd seen it done "better". 您的问题提到您看到它“做得更好”。 Could you elaborate a bit on this? 您能详细说明一下吗? I'm not quite sure what you mean. 我不太确定你的意思。

Here is a simple recursive algorithm: 这是一个简单的递归算法:

public Category FindCategory(Category category, string url)
{
    if(category.Url == url)
    {
        return category;
    }

    Category solution = null;    

    foreach(Category child in category.Children)
    {
        solution = FindCategory(child, url);
        if(solution != null)
        {
            return solution;
        }
    }

    return null;
}

I suppose you could use a stack data structure. 我想您可以使用堆栈数据结构。 Something like: 就像是:

public Category FindCategory(Category category, string url) {
    Stack<Category> categoryStack = new Stack<Category>();
    categoryStack.Push(category);
    while(categoryStack.Peek() != null) {
        Category cat = categoryStack.Pop();
        if(cat.Url == url) {
            return cat;
        }

        foreach(Category child in cat.Children) {
            categoryStack.Push(child);
        }
    }

    return null;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM