【问题标题】:Using recursion to create a path for child elements使用递归为子元素创建路径
【发布时间】:2012-02-17 21:15:11
【问题描述】:

我有一个基本类别对象,其中也包含子类别。这是我的对象结构的简化版本:

类别

int Id

string CategoryName

string Path

Category ParentCategory

List<Category> SubCategories

Computer
     --> Accessories
                 --> Keyboard
                 --> Mouse
     --> Storage
             --> Flash
             --> Micro

如何编写一个为所有类别创建路径的函数?

路径,我的意思是:

对于键盘:计算机/配件/键盘

配件:电脑/配件

对于计算机:计算机

【问题讨论】:

  • 这是作业吗?如果是这样,它应该被标记为这样。此外,如果我们为您工作,对您也没有多大好处。尝试解决问题,如果遇到特定困难,请向社区寻求帮助。
  • 这不是作业。我试图解决它几个小时。对象和关系可以显示我的工作复杂,所以我没有分享它,我也提到这是简化版本

标签: c# .net recursion


【解决方案1】:
// If grand parent category has null parent you can do

public toBreadCrumbs() {

    String out = this.CategoryName;

    for(Category aux = this.ParentCategory;aux != null;) {

        out = aux.CategoryName + ">" + out;

        aux = aux.ParentCategory;

    }

}

【讨论】:

    【解决方案2】:

    这可能会完成这项工作,尽管堆栈不是绝对必要的:

        public string Path
        {
            get
            {
                var pathStack = new Stack<Category>();
                var parentCategory = Parent;
    
                while (parentCategory != null)
                {
                    pathStack.Push(parentCategory);
                    parentCategory = parentCategory.ParentCategory ;
                }
    
                return String.Join("/", pathStack.Select(cat => cat.Name));
            }
        }
    

    【讨论】:

      【解决方案3】:

      这样的事情应该可以工作:

      public String getPath(Category cat)
      {
          if (cat.ParentCategory == null) return cat.CategoryName;
          return getPath(cat.ParentCategory) + "/" + cat.CategoryName;
      }
      

      【讨论】:

        【解决方案4】:
        Category cat=ParentCategory;
        StringBuilder sb=new StringBuilder(CategoryName);
        while (cat != null)
        {
          sb.Insert(0,cat.Name+"/");
          cat=cat.ParentCategory;
        }
        
        String path=sb.ToString();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-10-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多