在C#中使用无父节点构建锯齿状树

时间:2013-06-20 16:50:08

标签: c# linq-to-entities .net-4.5

我有一组相关项目列表,我需要从中创建树结构。然而,这些树节点中的一些是无父节点的,我想将这些节点中的每一个都粘贴到根节点中。使用LINQ和我的结果我创建了以下内容。但是,这不能处理分支中没有父节点的节点....

        var list = 
            (from o in resultList[QueryList.Length - 1].ToList()
            select new GroupItem
            {
                ItemCode = o.ItemCode,
                ItemDescription = o.ItemDescription,
                Items = (from tg in resultList[QueryList.Length - 2].ToList()
                        where tg.ParentCode == o.ItemCode
                        select new GroupItem
                        {
                            ItemCode = tg.ItemCode,
                            ItemDescription = tg.ItemDescription,
                            Items = (from t in resultList[QueryList.Length - 3]
                                    where t.ParentCode == tg.ItemCode
                                    select new GroupItem
                                    {
                                        ItemCode = t.ItemCode,
                                        ItemDescription = t.ItemDescription,
                                        Items = (from su in resultList[QueryList.Length - 4]
                                                where su.ParentCode == t.ItemCode
                                                select new SelectableItem
                                                {
                                                    ItemCode = su.ItemCode,
                                                    ItemDescription = su.ItemDescription,
                                                }).ToList()
                                    }).Cast<SelectableItem>().ToList()
                        }).Cast<SelectableItem>().ToList()
            }).Cast<SelectableItem>().ToList();

我真正想要的是......有没有办法通过LINQ to Objects快速轻松地完成这项工作?

Root
^
|
|____Node 1
|         |
|         |<------ Parent Relationship
|________Node 2
|             |
|             |  
|____________Node 3
   ^
   |
   |
   If no parent then add to root.

2 个答案:

答案 0 :(得分:1)

看起来你正试图做这样的事情:

List<List<GroupItem>> resultList = ...

var roots = new List<GroupItem>();

ICollection<GroupItem> parentLevel = roots;
foreach (var nodeLevel in resultList.AsEnumerable().Reverse())
{
    //Find each parent's child nodes:
    foreach (var parent in parentLevel)
    {
        parent.Items = nodeLevel.Where(node => node.ParentCode == parent.ItemCode)
                                .Cast<SelectableItem>().ToList();
    }

    //Add parentless nodes to the root:
    roots.AddRange(nodeLevel.Where(node => node.ParentCode == null));

    //Prepare to move to the next level:
    parentLevel = nodeLevel;
}

答案 1 :(得分:0)

完成所有这些之后:

resultList.ForEach(x => x.Where(tg => tg.ParentCode == null).ToList().ForEach(list.Add));