devendra
devendra

Reputation: 11

Make tree structure from list of objects in c#

I have a class called Detail as given below:

public class Detail
{
    public int Id { get; set; }
    public string Name { get; set; }
    public System.Nullable<int> ParentID { get; set; }
}

And I make a list of detail as given below:

        List<Detail> Details= new List<Detail>();

        Details.Add(new Detail { Id = 1, Name = "James", ParentID =null });
        Details.Add(new Detail { Id = 2, Name = "David", ParentID = 1 });
        Details.Add(new Detail { Id = 3, Name = "Richard", ParentID = 2 });
        Details.Add(new Detail { Id = 4, Name = "John", ParentID = 3 });
        Details.Add(new Detail { Id = 5, Name = "Robert", ParentID = 3 });
        Details.Add(new Detail { Id = 6, Name = "Paul", ParentID = 3 });
        Details.Add(new Detail { Id = 7, Name = "Kevin", ParentID = 2 });
        Details.Add(new Detail { Id = 8, Name = "Jason", ParentID = 7 });
        Details.Add(new Detail { Id = 9, Name = "Mark", ParentID = 7 });
        Details.Add(new Detail { Id = 10, Name = "Thomas", ParentID = 9 });
        Details.Add(new Detail { Id = 11, Name = "Donald", ParentID = 9 });

And now I want this Detail list convert into tree structure.

Upvotes: 1

Views: 6495

Answers (1)

Captain0
Captain0

Reputation: 2613

You can try the following

Add a new class to hold the tree object

public class TreeNode
{
  public int Id { get; set; }
  public string Name { get; set; }

  public TreeNode Parent { get; set; }
  public List<TreeNode> Children{ get; set; }
}

Then add a recursive method to build the tree

private static List<TreeNode> FillRecursive(List<Detail> flatObjects, int? parentId=null)
{
  return flatObjects.Where(x => x.ParentID.Equals(parentId)).Select(item => new TreeNode
  {
    Name = item.Name, 
    Id = item.Id, 
    Children = FillRecursive(flatObjects, item.Id)
  }).ToList();
}

Then call it where you need it

 var tree = FillRecursive(Details,null);

Upvotes: 4

Related Questions