从列表列表c#创建树

我有一个问题,从字符串列表列表创建树.

这是我的输入数据:

    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

有人能指点我一个递归方法,让我从列表中填写树吗?

提前致谢

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

最佳答案

    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中生成的树看起来与您的完全不同.

点赞