【问题标题】:Read up to nth level of list using Linq and save required data to another list使用 Linq 最多读取第 n 级列表并将所需数据保存到另一个列表
【发布时间】:2015-09-18 12:38:18
【问题描述】:

我有一个包含第 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 级的数据,因为它缺少读取数据的递归方法。如何将此转换为递归方法或有其他方法可以做到这一点。

【问题讨论】:

  • 你的意思是如何flatten hierarachy
  • 我看到这个帖子但我真的不想使用堆栈
  • @Muhammadzubair - 你的代码不工作吗?输出应该是什么样子?
  • 我的代码正在运行,但它读不到第 n 级。它读取到第三级。我需要读到第 n 级。

标签: c# linq list tree


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-22
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多