使用 Linq 读取最多 n 级列表并将所需数据保存到另一个列表

Read up to nth level of list using Linq and save required data to another list

我有一个包含第 n 级子对象的列表。我想遍历列表并使用 Linq 将所需数据获取到另一个具有不同结构的列表。

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

我有包含数据的 IEnumerable 列表。

具有第 n 级子节点的节点列表

我正在使用 Linq 创建一个包含 Linq 数据的新对象。

这是我创建新对象的代码

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
            })
        })
    });
}

它没有给我第 n 级的数据,因为它缺少读取数据的递归方法。如何将其转换为递归方法或是否有其他方法。

我相信这会如你所愿。在递归调用函数之前,您已经声明了函数。

// 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();

更新

随着 C# 7 中局部函数的引入,您现在可以像通常定义函数一样在函数内定义函数,递归也很简单。

// 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();