根据平面表中的父子关系创建树 [英] Creating a tree from Parent/Child relation represented in a flat table
问题描述
我有一个由存储过程返回的以下字段的C#列表:
I have a C# List of following fields which are returned by a stored procedure:
CarrierId ParentCarrierId Name Descrition
1 NULL A AA
2 1 B BB
3 1 C CC
4 3 D DD
5 NULL E EE
我需要从输出中构造一个嵌套的对象列表
I need to construct a nested object list out of this output
因此,运营商的每个对象都应具有其所有子代的列表.谁能帮我构造一个LINQ代码来实现这一目标?
So each object of Carrier should have list of all it's children. Can anyone help me construct a LINQ code to accomplish this?
所需结果:
CarrierId = 1
|__________________ CarrierId = 2
|
|__________________ CarrierId = 3
|
| |___________________ CarrierId = 4
CarrierId = 5
所需结果应如上所述
以下代码将内容排列在树中,但是一个孩子仍然出现在列表中
the following code arrange things in tree but a child still appears in the list
c.Children = carrierList.Where(child => child.ParentCarrierId == c.CarrierId).ToList();
CarrierId = 1
|
|__________________ CarrierId = 2
|
|__________________ CarrierId = 3
| |___________________ CarrierId = 4
|
CarrierId = 2
|
CarrierId = 3
|
CarrierId = 4
|
CarrierId = 5
我不希望这种行为.如果出现孩子"字样,应将其从根目录中删除.
I don't want this behavior. If something appeared as Child it should be removed from root.
推荐答案
这就是您所需要的.
首先,从源数据开始:
var source = new []
{
new { CarrierId = 1, ParentCarrierId = (int?)null, Name = "A", Description = "AA", },
new { CarrierId = 2, ParentCarrierId = (int?)1, Name = "B", Description = "BB", },
new { CarrierId = 3, ParentCarrierId = (int?)1, Name = "C", Description = "CC", },
new { CarrierId = 4, ParentCarrierId = (int?)3, Name = "D", Description = "DD", },
new { CarrierId = 5, ParentCarrierId = (int?)null, Name = "E", Description = "EE", },
};
然后,通过ParentCarrierId
创建查找:
var lookup = source.ToLookup(x => x.ParentCarrierId);
现在我们需要一个输出结构:
Now we need an output structure:
public class Carrier
{
public int Id;
public List<Carrier> Children = new List<Carrier>();
public string Name;
public string Description;
}
然后,一个build
函数通过ParentCarrierId
弹出所有载波:
Then, a build
function to pop all of the carriers out by ParentCarrierId
:
Func<int?, List<Carrier>> build = null;
build = pid =>
lookup[pid]
.Select(x => new Carrier()
{
Id = x.CarrierId,
Name = x.Name,
Description = x.Description,
Children = build(x.CarrierId),
})
.ToList();
注意:它是递归的,因此需要使用初始的= null
定义.
NB: It's recursive so it needs to be defined with the initial = null
.
最后我们构建:
List<Carrier> trees = build(null);
这给出了:
这篇关于根据平面表中的父子关系创建树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!