0

我有一個文件夾結構表示爲父/子關係樹。現在讓我們想象一下下面的樹:向上走父母/子關係樹

- Folder1中

--- Subfolder1-1

---- Subfolder1-1-1

--- Subfolder2

----子文件夾2-1

- 文件夾2

現在我明顯得到了導航屬性的使用,所以當Subfolder1-1裏面有一個屬性ParentFolder時,代表Folder1

我現在怎麼走上樹來生成文件夾名稱中的連接字符串?

例如,當從Subfolder1-1-1調用此方法時,我希望字符串爲Folder1.Subfolder1-1.Subfolder1-1-1,當從Subfolder2-1調用時,我希望字符串爲Folder1.Subfolder2.Subfolder2-1

我想過遞歸,但下面不工作:

public string GetCompleteFolderName(string delimiter) 
{ 
    string folderName = null; 

    if (FolderParent != null) 
    { 
     folderName += GetCompleteFolderName(FolderParent) + delimiter; 
    } 

    return folderName; 
} 

private string GetCompleteFolderName(Folder folder) 
{ 
    string folderName = null; 
    if (folder != null) 
    { 
     folderName = folder.Name; 
    } 

    return folderName; 
} 

回答

1

認爲這應該做的伎倆

public class Folder 
{ 
    public Folder ParentFolder { get; set; } 
    public string Name { get; set; } 

    public Folder() 
    { 
    } 
    public string GetFullFolderName(string delimiter = ".") 
    { 
     var folderName = string.Empty; 
     if (ParentFolder != null) 
     { 
      folderName += ParentFolder.GetFullFolderName(delimiter) + delimiter + Name; 
     } 
     else 
     { 
      folderName += Name; 
     } 
     return folderName; 
    } 
} 

internal class Program 
{ 
    private static void Main(string[] args) 
    { 
     var f1 = new Folder {Name = "f1"}; 
     var f2 = new Folder {Name = "f2", ParentFolder = f1}; 
     var f3 = new Folder {Name = "f3", ParentFolder = f2}; 

     Console.WriteLine(f3.GetFullFolderName()); 
    } 
} 

輸出:f1.f2.f3

+0

究竟是什麼我想了。恭喜您的第一個聲望,並感謝您! – SeToY