在c#中生成递归对象列表

  • 本文关键字:递归 对象 列表 c#
  • 更新时间 :
  • 英文 :


我有如下的类模型:

public class ABC
{
public string value { get; set; }
public List<ABC> children { get; set; }
}

并像这样构造数据

Parent   Value
1       A
A       C
2       B
B       D

我想递归地构建一个复杂对象。我已经设法递归地将Children添加到Children中。

如何返回下面类似List<ABC>的结果?
[
{
value: '1',
children: [
{
value: 'A',
children: [
{
value: 'C',
},
],
},
],
},
{
value: '2',
children: [
{
value: 'B',
children: [
{
value: 'D',
},
],
},
],
},
];

这个示例输出您所期望的结果,包含更多的子节点。

using System;
using System.Collections.Generic;
using System.Text.Json;
public class Json
{
public class ABC
{
public string value { get; set; }
public List<ABC> children { get; set; }
}
public void Run()
{
var abcs = new List<ABC>();
abcs.Add(new ABC()
{
value = "1",
children = new List<ABC>()
{
new ABC() { value = "A", children = new List<ABC>() {
new ABC() { value = "C" }
}},
new ABC() { value = "F" }
}
});
abcs.Add(new ABC()
{
value = "2",
children = new List<ABC>()
{
new ABC() { value = "B", children = new List<ABC>() {
new ABC() { value = "D" }
}},
new ABC() { value = "G" }
}
});
var ser = JsonSerializer.Serialize(abcs, new JsonSerializerOptions() { WriteIndented = true, DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull });
Console.WriteLine(ser);
}
}

最新更新