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

Raj
Raj
Member
46 Points
13 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: 50
Total Answered: 1
Total Marked As Answer: 0
Posted On: 12-May-2022 22:09

Share:   fb twitter linkedin
Answers
Rahul Maurya
Rahul M...
Teacher
1392 Points
236 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
 Log In to Chat