I have a folder hierarchy where a folder can have a parent folder, with unlimited depth.
So…
Folder A
FolderId = 1
ParentFolderId = Null (Top Level)
Folder B
FolderId = 2
ParentFolderId = 1 (Nested under A)
Folder C
FolderId = 3
ParentFolderId = 2 (Nested under B)
Folder D
FolderId = 4
ParentFolderId = 3 (Nested under C)
I want to get all of the children of Folder B (or whatever folder the user has selected) so that I can delete all of the children, but leave the parents (unless, of course, the top level folder is selected).
This is probably some fairly straightforward recursion or a foreach loop, but I’m struggling with it this morning! I’m using C# and EF, so something using that would be most helpful. I’d like the result as a flat list, if possible.
Ideally, I’d like to have it as a method off my custom Folder object so that any folder I have, I can just say Folder.Children() or something like that.
Folder Object:
public class Folder
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int? ParentId { get; set; }
public virtual Folder Parent { get; set; }
public virtual ICollection<File> Files { get; set; }
}
Thank you in advance.
Here is a recursive method which will do what you want. You call this method with a argument of Id of folder which child you want to get and it will retrive all child and childs-of-childs and so-so-so.