2012-01-24 71 views
0

我有一個基本的類別對象,它也有子類別。這是我的對象結構的簡化版本:使用遞歸創建子元素的路徑

類別

int Id 

string CategoryName 

string Path 

Category ParentCategory 

List<Category> SubCategories 

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

我怎麼能寫會爲所有的類路徑的功能?

通過的路徑,我的意思是:

對於鍵盤:電腦/配件/鍵盤

對於配件:電腦/配件

計算機:計算機

+1

這是功課?如果是這樣,它應該被標記爲這樣。此外,如果我們爲你做你的工作,這不會對你有多大的益處。嘗試解決問題,如果遇到特定困難,請向社區提供幫助。 – StriplingWarrior

+0

這不是一項家庭作業。我試圖解決它幾個小時。對象和關係可以顯示我的工作複雜,所以我沒有分享它,我也提到這是簡化版本 –

回答

2

像這樣的東西應該工作:

public String getPath(Category cat) 
{ 
    if (cat.ParentCategory == null) return cat.CategoryName; 
    return getPath(cat.ParentCategory) + "/" + cat.CategoryName; 
} 
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; 

    } 

} 

1
Category cat=ParentCategory; 
StringBuilder sb=new StringBuilder(CategoryName); 
while (cat != null) 
{ 
    sb.Insert(0,cat.Name+"/"); 
    cat=cat.ParentCategory; 
} 

String path=sb.ToString(); 
1

這可能會做的工作,雖然堆棧並非絕對必要:

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)); 
     } 
    }