Search code examples
javascriptc#arraystreeviewbootstrap-treeview

Remove empty nodes in a c# List


I have a C# object which after JSON Serialization becomes something like this:

var tree = [{
Id:1,
text: "Parent 1",
ParentId:0
nodes: [
  {
    Id:2,
    text: "Child 1",
    ParentId:1
    nodes: [
      {
        Id:3
        text: "Grandchild 1",
        ParentId:2,
        nodes:[]
      },
      {
        Id:4,
        text: "Grandchild 2",
        ParentId:2,
        nodes: []
      }
    ]
  },
  {
    Id:5
    text: "Child 2",
    ParentId:1,
    nodes: []
  }
]
},
{
Id:6,
text: "Parent 2",
ParentId:0
nodes: []
}];

I want to remove all nodes that are empty i.e. [] from the object or just mark them as null , so my final object will look like

var tree = [{
Id:1,
text: "Parent 1",
ParentId:0
nodes: [
  {
    Id:2,
    text: "Child 1",
    ParentId:1
    nodes: [
      {
        Id:3
        text: "Grandchild 1",
        ParentId:2,
        nodes:null
      },
      {
        Id:4,
        text: "Grandchild 2",
        ParentId:2,
        nodes:null
      }
    ]
  },
  {
    Id:5
    text: "Child 2",
    ParentId:1,
    nodes:null
  }
]
},
{
Id:6,
text: "Parent 2",
ParentId:0
nodes:null
}];

The list is dynamic and can have many branches.Thanks. My C# class is this

public class Tree
{
    public int Id { get; set; }
    public string text { get; set; }
    public int ParentId { get; set; }
    public List<Tree> nodes { get; set; }
}

For creating the tree List Object my function :

var treeItems = new List<Tree>(); //Contails Flat Data No tree
treeItems = SomeMethod(); //To populate flat Data
treeItems.ForEach(item => item.nodes = treeItems.Where(child => child.ParentId == item.Id).ToList());

Now I Get the Tree structure in

var tree = treeItems.First();

I need some logic so that it will put all nodes = null in all nested levels using linq preferably. So that I can use it bootstrap-treeview datasource.


Solution

  • var treeItems = new List<Tree>(); //Contails Flat Data No tree
    treeItems = SomeMethod(); //To populate flat Data
    treeItems.ForEach(item => item.nodes = treeItems.Where(child => child.ParentId == item.Id).Any()?treeItems.Where(child => child.ParentId == item.Id).ToList():null);