gpt4 book ai didi

c# - 从平面表中表示的父/子关系创建树

转载 作者:行者123 更新时间:2023-11-30 14:07:52 25 4
gpt4 key购买 nike

我有一个由存储过程返回的以下字段的 C# 列表:

CarrierId   ParentCarrierId Name Descrition
1 NULL A AA
2 1 B BB
3 1 C CC
4 3 D DD
5 NULL E EE

我需要根据这个输出构造一个嵌套的对象列表

所以 Carrier 的每个对象都应该有它所有子对象的列表。任何人都可以帮助我构建 LINQ 代码来完成此任务吗?

期望的结果:

  CarrierId = 1
|__________________ CarrierId = 2
|
|__________________ CarrierId = 3
|
| |___________________ CarrierId = 4
CarrierId = 5

期望的结果应该如上所述

下面的代码在树中排列事物,但一个 child 仍然出现在列表中

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

我不想要这种行为。如果某物显示为 Child,则应将其从 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);

现在我们需要一个输出结构:

public class Carrier
{
public int Id;
public List<Carrier> Children = new List<Carrier>();
public string Name;
public string Description;
}

然后,一个 build 函数通过 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 来定义它。

最后我们构建:

List<Carrier> trees = build(null);

这给出:

trees

关于c# - 从平面表中表示的父/子关系创建树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37942259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com