Linq-如何循环树数据结构以构建树样式对象 [英] Linq - how to loop a tree data structure to build a tree style object
问题描述
我有以下SQL表数据:
I have the following SQL table data:
视觉树应如下所示:
要获取我正在使用的最高节点:
To get the very top nodes I'm using:
var parentNodes = data
.Where(i => i.AncestorId == i.DescedantId &&
(data.Count(d => d.DescedantId == i.DescedantId) == 1))
.ToList();
关于如何构建将循环遍历结构然后构建树样式对象的函数的任何线索吗?
Any clue on how to build a function that would loop trough the structure and then build the tree style object?
我的树样式对象类是:
public class ProfitCenterRoot
{
public List<ProfitCenterItem> Data { get; set; }
}
public class ProfitCenterItem
{
public int AncestorId { get; set; }
public int DescendantId { get; set; }
public string Text { get; set; }
public bool Leaf { get; set; }
// These are the child items
public List<ProfitCenterItem> Data { get; set; }
}
推荐答案
您可以使用递归将子级添加到每个父级.但是首先,我将向您的类添加默认构造函数以初始化数据列表:
You can use recursion to add children to each parent. But first, I would add a default constructor to your classes to initialize the Data lists:
public class ProfitCenterRoot
{
public List<ProfitCenterItem> Data { get; set; }
public ProfitCenterRoot()
{
Data = new List<ProfitCenterItem>();
}
}
public class ProfitCenterItem
{
// Existing properties here
public ProfitCenterItem()
{
Data = new List<ProfitCenterItem>();
}
}
然后,您可以创建一个简单的方法,该方法接受一个Parent和一个所有孩子的列表,将孩子递归地添加到父孩子的每个孩子,然后将孩子添加到父孩子:
Then you can create a simple method that takes in a Parent and a list of all children, recursively add children to each child of the parent, and then add the children to the parent:
public static void AddChildren(ProfitCenterItem parent,
IEnumerable<ProfitCenterItem> allChildren )
{
var children = allChildren
.Where(child =>
child.AncestorId == parent.DescendantId &&
child.AncestorId != child.DescendantId)
.ToList();
foreach (var child in children)
{
AddChildren(child, allChildren.Except(children));
parent.Data.Add(child);
}
}
因此,要填充对象,您可以执行以下操作:
So to populate your objects, you could then do:
var parentNodes = data
.Where(i => i.AncestorId == i.DescendantId &&
(data.Count(d => d.DescendantId == i.DescendantId) == 1))
.ToList();
var root = new ProfitCenterRoot();
foreach (var parentNode in parentNodes)
{
AddChildren(parentNode, data.Except(parentNodes));
root.Data.Add(parentNode);
}
这篇关于Linq-如何循环树数据结构以构建树样式对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!