-1

i have a method GetChild(id) that return the children with respect to id of parent passed as a parameter
those children can also have their own children to any level

if i want to create a JSON which represent the entire hierarchy of child and parent then how should i proceed?

public ActionResult GetChild(long id)

{
    Dal objDal = new Dal();
    var res = objDal.db.ChildGet(id).ToList();
    return Json(res, JsonRequestBehavior.AllowGet);
}

this is justfor first level

how can i use this GetChild(id) method recursively?

any kind of help will be appreciated

Mohd Maaz
  • 267
  • 5
  • 20
  • Refer [this answer](https://stackoverflow.com/questions/46560515/how-to-create-dynamic-menu-using-tree/46562343#46562343) for a typical example –  Apr 20 '18 at 09:14

1 Answers1

0
    public class Comment
    {
        public int Id { get; set; }
        public int ParentId { get; set; }
        public string Text { get; set; }
        public List<Comment> Children { get; set; }
    }
    public JsonResult Test()
    {
        List<Comment> categories = new List<Comment>()
        {
            new Comment () { Id = 1, Text = "Yabancı Dil", ParentId = 0},
            new Comment() { Id = 2, Text = "İngilizce", ParentId = 1 },
            new Comment() { Id = 3, Text = "YDS", ParentId = 2 },
            new Comment() { Id = 4, Text = "TOEFL", ParentId = 2 },
            new Comment() { Id = 5, Text = "YDS Seviye1", ParentId = 3 },
            new Comment() { Id = 6, Text = "TOEFL Seviye1", ParentId = 4 }
        };

        List<Comment> hierarchy = new List<Comment>();

        hierarchy = categories
                        .Where(c => c.Id == 2)
                        .Select(c => new Comment()
                        {
                            Id = c.Id,
                            Text = c.Text,
                            ParentId = c.ParentId,
                            Children = GetChildren(categories, c.Id)
                        })
                        .ToList();

        List<Comment> list = new List<Comment>();
        List<string> list2 = new List<string>();
        if (hierarchy != null)
        {
            liste.AddRange(hierarchy);

        }

        return Json(liste, JsonRequestBehavior.AllowGet);
    }

    public static List<Comment> GetChildren(List<Comment> comments, int parentId)
    {
        hAbDbContext db = new hAbDbContext();
        return comments
                .Where(c => c.ParentId == parentId)
                .Select(c => new Comment()
                {
                    Id = c.Id,
                    Text = c.Text,
                    ParentId = c.ParentId,
                    Children = GetChildren(comments, c.Id)
                })
                .ToList();
    }
Onur Önder
  • 311
  • 1
  • 7
  • 20
  • 1
    Please add explanation or details to your answer so that all readers understand what you've achieved there and not just providing code dump. – Tetsuya Yamamoto Apr 20 '18 at 09:43