我需要创建一个方法,通过嵌套列表中的实体的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”作为参数调用方法,它应该返回每个节点的节点Path:
{ "D:\Windows", "Microsoft.net", "Framework", "v3.0" }
答案 0 :(得分:0)
您当前的设计使它有点棘手,我会向您的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
,以便它可以继承所有相同的属性/行为,而无需复制代码。