How to get all child folder in a self join entity c#?

Raj
Raj
648 Points
26 Posts

I have self reference entity like as:

public class Folder
    {
        public int Id { get; set; }
        public int ParentId { get; set; }
        public string Name { get; set; }
    }

For example:

class Program
{
        static void Main(string[] args)
        {
            var list = new List<Folder>() {
                new Folder() { Id = 1, ParentId = 0, Name = "A" },
                new Folder() { Id = 2, ParentId = 1, Name = "A.1" },
                new Folder() { Id = 3, ParentId = 1, Name = "A.2" },
                new Folder() { Id = 4, ParentId = 3, Name = "A.2.i" },
                new Folder() { Id = 5, ParentId = 3, Name = "A.2.ii" }
            };

            GetAllChild(<folderId>, list);

        }
}

I want a method to return all child folders of provided folder id.

 

Views: 800
Total Answered: 1
Total Marked As Answer: 1
Posted On: 12-May-2022 22:09

Share:   fb twitter linkedin
Answers
Rahul Maurya
Rahul M...
4896 Points
25 Posts
         

Try following method with Linq:

IEnumerable<Folder> GetAllChild(int id, List<Folder> folder)
{
    return folder.Where(x => x.ParentFolderId == id || x.Id == id)
                .Union(folder.Where(x => x.ParentFolderId == id)
                            .SelectMany(y => GetChild(y.Id))
    );
}    
Posted On: 12-May-2022 22:30
thanks
 - Raj  01-Aug-2022 23:08
 Log In to Chat