0

我有一组相关项目列表,我需要从中创建树结构。但是,其中一些树节点是无父节点的,我想将这些节点中的每一个都粘贴到根中。使用 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.
4

2 回答 2

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;
}
于 2013-06-20T20:05:51.097 回答
0

在你完成所有这些之后:

resultList.ForEach(x => x.Where(tg => tg.ParentCode == null).ToList().ForEach(list.Add));
于 2013-06-20T17:08:54.393 回答