检查级别未知的嵌套列表中的 属性 值

Check property value in nested list with unknown levels

我有一个嵌套菜单 - 这里是一个简化的 class:

public class NestedNode
{
    public string Url { get; set; }
    public List<NestedNode> Children { get; set; }
}

鉴于我有一个 NestedNode 的递归列表,我正在尝试确定是否有任何后代在任何级别处于活动状态。

这是要测试的代码:

protected void Page_Load(object sender, EventArgs e)
{
    // The url of the current page
    var currentUrl = Request.Url.GetLeftPart(UriPartial.Path);

    // This is a list of nested nodes
    var nodes = SiloNodes;

    // Start loop
    RecursiveCall(nodes, currentUrl);
}

void RecursiveCall(IEnumerable<NestedNode> nodes, string currentUrl)
{
    if (nodes == null) return;

    foreach (var n in nodes)
    {
            // This can test current level only
            //var isActive = n.Url == currentUrl;

            // This can test next level down
            //var isActive = n.Children.Any(c => c.Url == currentUrl);

            // How can I test all levels in one go?

            RecursiveCall(n.Children, currentUrl);
    }
}

我需要做的是计算 parents children 是否处于活动状态(在顶层),以便我可以添加 classes。目前,我的想法只有一个层次。

在这种情况下,我可能会向 NestedNode 添加一个方法来递归地检查条件 - 像这样:

public bool ExistsRecursive(Func<NestedNode, bool> predicate)
{
    if(predicate(this))
    {
        return true;
    }
    foreach(var node in Children)
    {
        return predicate(node);
    }
    return false;
}

然后,在您的 Page_Load 中,您只需要:

if(nodes.ExistsRecursive(n => n.Url == currentUrl))
{
    // current url is found in at least one node
}

怎么样

void Main()
{
    var nodes = new List<NestedNode>();

    var isActive = nodes.Any(n => n.AnyActive("url"));
}

public class NestedNode
{
    public NestedNode()
    {
        Children = Enumerable.Empty<NestedNode>();
    }
    public string Url { get; set; }
    public IEnumerable<NestedNode> Children { get; set; }

    public bool AnyActive(string url){ return Url==url || Children.Any(c => c.AnyActive(url));}
}