【问题标题】:Get full path to nested list获取嵌套列表的完整路径
【发布时间】:2012-09-11 12:30:53
【问题描述】:

我需要创建一个方法,通过嵌套列表中实体的 ID 查找根节点的路径。

public class Application
{
    public string Name { get; set; }
    public string Path { get; set; }
    public List<Component> Components { get; set; }
}

public class Component
{
    public string Name { get; set; }
    public string Path
    public List<Component> Components { get; set; }
}

例如:

-Name: Windows: 
-Path: "D:\Windows"
-components:
[0] Path: "Microsoft.net"
    Name: ".netfolder"
    Components: 
    [0] Path: "Framework"
        Name: ".netfolder"
        Components: 
        [0] Path: "v3.0"
            Name: "3.0folder"
            Components: 
    [1] Path: "Microsoft.net"
        Name: "Framework64"
        Components: 

如果我以“3.0folder”作为参数调用该方法,它应该返回每个节点的节点路径:

{ "D:\Windows", "Microsoft.net", "Framework", "v3.0" }

【问题讨论】:

  • 组件是否又像your last question 那样递归?您至少应该为列表的初始化提供有意义的示例数据。这将有助于我们为您提供帮助。
  • 蒂姆你是完全正确的。我正在研究一个递归模型来解释东西是如何组织的。我会改进这个例子,让你有更好的想法。
  • 在那里,我改进了模型,例如,一切。谢谢蒂姆。

标签: c# recursion nested


【解决方案1】:

您当前的设计有点棘手,我会为您的Component 类引入一个父级,这将允许您向上遍历层次结构并构建路径。这意味着您只需要担心找到组件即可。

您也可以对搜索执行相同的操作,只是这次遍历层次结构,例如

public class Component
{
    public Component Parent { get; set; }
    public string Path { get; set; }
    public string Name { get; set; }
    public List<Component> Components { get; set; }
    public Component FindByName(string searchTerm)
    {
        if (searchTerm == Name)
            return this;

        var result = null;
        foreach (var c in Components)
        {
            var result = c.FindByName(searchTerm);
            if (result != null) 
                break;
        }
        return result;
    }

    public string FullPath
    {
        get { return this.GetFullPath(); }   
    }

    private string GetFullPath()
    {
        var fullPath = Path;
        var parent = Parent;
        while (parent != null)
        {
            fullPath = String.Format("{0}{1}{2}", parent.FullPath, System.IO.Path.DirectorySeparatorChar, fullPath)
        }
        return path;
    }
}

代码未经测试,但您明白了。每个组件都有向上/向下遍历树所需的信息。

另外,您应该让Application 派生自Component,这样它就可以继承所有相同的属性/行为而无需复制代码。

【讨论】:

    猜你喜欢
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    • 2017-03-16
    • 2014-12-14
    • 1970-01-01
    相关资源
    最近更新 更多