Skip to main content
 首页 » 编程设计

c#之递归搜索类别及其子项

2024年02月23日17jiqing9006

我有以下类(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; } 
} 

现在给出一个类别和 url 的实例。我希望获得 URL 与类别或其任何子项(或他们的子项等)匹配的类别。

因此我的函数将具有以下签名:

public Category FindCategory(Category category, string url); 

我知道递归是要走的路,我已经设法想出了一个解决方案。但是我确实看到它做得更好,但我找不到在哪里。如果有人能向我展示实现此目标的最简单、最干净的方法,我将不胜感激。

谢谢

请您参考如下方法:

就递归而言,答案非常简单。不过,与 null 返回相比,我更喜欢 Try 模式。

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; 
} 

你的问题提到你看到它做得“更好”。你能详细说明一下吗?我不太确定你的意思。