gpt4 book ai didi

c# - 从列表列表创建树 C#

转载 作者:行者123 更新时间:2023-11-30 12:56:27 24 4
gpt4 key购买 nike

我在从字符串列表创建树时遇到问题。这是我的输入数据:

    IReadOnlyList<IReadOnlyList<string>> listeDesParcours = new List<IReadOnlyList<string>>
{
new List<string>
{
"Produit","Sinistre","Particulier","Auto","RC"
},
new List<string>
{
"Produit","Sinistre","Entreprise","Auto","2roues"
},
new List<string>
{
"Produit","reclamation","Particulier","Moto","PP"
},
new List<string>
{
"Produit","reclamation","Entreprise","Auto","TT"
},
new List<string>
{
"Produit","reclamation","Entreprise","Auto","PP"
},
new List<string>
{
"Produit","souscription","Salarie","Aviation"
},
new List<string>
{
"Produit","souscription","Salarie","Aviation","Airbus"
},
new List<string>
{
"Produit","reclamation","Reclamation tout court"
},
new List<string>
{
"Produit","Produit tout court"
},
new List<string>
{
"Produit","Sinistre","Entreprise","Auto","5roues"
}
};

如您所见,它是一个字符串列表列表,我想从中获取一棵树.这是我最后要返回的对象

 public class Node
{
public string Value { get; set; }
public List<Node> Childs { get; set; }
}

这就是我想要的结构

                                 RootElement
|
___________________________Produit__________________________
/ | \
__sinistre___________ reclamation_______ Souscription
| \ / \ |
entreprise particulier entreprise particulier Salarie______________
| | | | | \
auto auto auto auto Marine Aviation__
/ \
Airbus Boing

谁能给我指出一个递归方法,让我可以从列表的列表中填充树?

提前致谢

编辑:在最后一条评论之后我想澄清一下我想获取我创建的节点类型的对象......但是我的输入是字符串列表

最佳答案

    var root = new Node() { Value = "RootElement", Childs = new List<Node>() };
foreach (var route in listeDesParcours)
{
var current = root;
foreach (var value in route)
{
var child = current.Childs.Find(x => x.Value == value);
if (child == null)
{
child = new Node() { Value = value, Childs = new List<Node>() };
current.Childs.Add(child);
}
current = child;
}
}

请注意,listeDesParcours 中的数据与绘制的树之间存在一些差异,因此 root 中生成的树看起来完全喜欢你的。

关于c# - 从列表列表创建树 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40849968/

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