【问题标题】:C# path list to tree with objects带有对象的树的 C# 路径列表
【发布时间】:2012-10-21 11:29:09
【问题描述】:

我需要用路径列表中的对象构建一个树列表。下面的代码有效,但我无法从搜索功能中检索完整路径。请参阅粗体代码...

public List<RestoreTreeViewModel> BuildTree(IEnumerable<string> strings)
{
    return (
      from path in strings
      let split = path.Split('\\')
      group path by path.Split('\\')[0] into g
      select new RestoreTreeViewModel()
      {
          Name = g.Key,
          Nodetype = 2,
          CanReference = true,
          **FullPath = path;**
          Children = BuildTree(            
            from s in g
            where s.Length > g.Key.Length + 1
            select s.Substring(g.Key.Length + 1)) 
      }
      ).ToList();
}

这可以工作还是我应该研究另一种从路径列表构建树的方法?

【问题讨论】:

  • public List BuildTree(IEnumerable strings) { return ( from path in strings let split = path.Split('\\') group path by path.Split('\\ ')[0] into g select new RestoreTreeViewModel() { Name = g.Key, Fullpath = path; Nodetype = 2, CanReference = true, Children = BuildTree( from s in g where s.Length > g.Key.Length + 1 选择 s.Substring(g.Key.Length + 1)) } ).ToList(); }

标签: c# object tree filelist


【解决方案1】:

您需要在 BuildTree() 方法中添加一个列表参数,然后将项目附加(或前置)到该列表,以便最终结果将包含路径中的所有项目。

还有其他方法可以解决它,但如果我理解你想要做什么,这似乎很简单。

【讨论】:

  • 感谢您的回复。我需要将“路径”字符串放入选择块中,因为我需要填充完整路径字符串作为列表循环的一部分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-07
  • 1970-01-01
  • 2015-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多