2

I have a list with nth level of children object. I want to traverse through the list and get required data to another list having different structure using Linq.

public class Node
{
    public List<Node> Children = new List<Node>();
    public Node Parent { get; set; }
    public FolderReportItem AssociatedObject { get; set; }
}

I have list of IEnumerable which contains data. list of nodes with child up to nth level

list of nodes with child up to nth level

I am using Linq to create a new object with linq data.

Here is code how I am creating new object

var jsonTree = new List<object>();

foreach (var node in nodesList)
{
    jsonTree.Add(new
    {
        id = node.AssociatedObject.ID,
        name = node.AssociatedObject.Name,
        children = node.Children.Select(p => new
        {
            id = p.AssociatedObject.ID,
            name = p.AssociatedObject.Name,
            children = p.Children.Select(q => new
            {
                id = q.AssociatedObject.ID,
                name = q.AssociatedObject.Name
            })
        })
    });
}

It is not giving me data to nth level as it missing recursive method to read data. How to transfer this to recursive method or is there other way to do this.

Jason Boyd
  • 6,839
  • 4
  • 29
  • 47
Muhammad zubair
  • 291
  • 2
  • 6
  • 20

1 Answers1

2

I believe this will do what you want. Before you can call a function recursively you have declare the function.

// Declare the function so that it can be referenced from within
// the function definition.
Func<Node, object> convert = null;

// Define the function.
// Note the recursive call when setting the 'Children' property.
convert = n => new 
{
    id = n.AssociatedObject.ID,
    name = n.AssociatedObject.Name,
    children = n.Children.Select(convert)
};

// Convert the list of nodes to a list of the new type.
var jsonTree = 
    nodes
    .Select(convert)
    .ToList();

Update

With the introduction of local functions in C# 7 you can now define a function within a function as you would normally define a function and recursion simply works.

// Declare and define the function as you normally would.
object convert (Node node)
{
    id = n.AssociatedObject.ID,
    name = n.AssociatedObject.Name,
    children = n.Children.Select(convert);
};

// Convert the list of nodes to a list of the new type.
var jsonTree = 
    nodes
    .Select(convert)
    .ToList();
Jason Boyd
  • 6,839
  • 4
  • 29
  • 47