C#中树状结构的三个相关列表

时间:2017-09-28 11:41:28

标签: c# linq treeview

我有三个清单。 LevelOne的Id是LevelTwo的Parent,LevelTwo的Id是Level3的Parent。

public class AllLevels
{
    public string Id {get;set;}
    public string Desc {get;set;}
    public bool HasChild {get;set;}
    public IList<AllLevels> {get;set;}
}

我正在尝试将这三个列表合并到一个列表中,该列表将具有类似LevelOne ID结构的树。

AllLevels
{
    Level
    {
        Id = "ABC",
        Desc = "SomeDesc",
        HasChildLevel = true,
        childLevel = 
        {
            Id = "123A",
            Desc = "SomeDesc",
            hasChildLevel = true,
            ChildLevel =
            {
                Id = "XYZ1",
                Desc = "Some Desc",
                HasChildLevel = false
            },
            ChildLevel =
            {
                Id = "XYZ2",
                Desc = "Some Desc",
                HasChildLevel = false
            }
        },
        childLevel = 
        {
            Id = "123B",
            Desc = "SomeDesc",
            hasChildLevel = true,
            ChildLevel =
            {
                Id = "XYZ3",
                Desc = "Some Desc",
                HasChildLevel = false
            }
        }
    },
    Level
    {
        Id = "XYZ",
        Desc = "Some Desc",
        HasChildLevel = true
        ChildLevel =
        {
            Id = "123D",
            Desc = "Some Desc",
            HasChild = true,
            ChildLevel = 
            {
                Id = "XYZ4",
                Desc = "Some Desc",
                HasChild = false
            }
        }
    },
    Level
    {
        Id = "DEF",
        Desc = "Some Desc",
        HasChildLevel = false
    }
}

示例输出将是这样的

enter

是否有通过LINQ的方法我可以在不使用嵌套的foreach循环的情况下执行此过程? 我在Stackover流程中经历了很多帖子,但我无法找到将三个相关列表合并到层次结构中的技术。 如果有人提到网站,我可以得到一些也有帮助的想法。

1 个答案:

答案 0 :(得分:0)

如果你从未超过三个级别,那么下面是一个相对可读的解决方案。但它不是一般问题的通用解决方案。

        var result = levelOne
            .Select(l1 => new AllLevels
            {
                Id = l1.Id,
                Desc = l1.Desc,
                HasChild = levelTwo.Any(l2 => l2.Parent == l1.Id),
                Children = levelTwo.Where(l2 => l2.Parent == l1.Id)
                .Select(l2 => new AllLevels
                {
                    Id = l2.Id,
                    Desc = l2.Desc,
                    HasChild = levelThree.Any(l3 => l3.Parent == l2.Id),
                    Children = levelThree.Where(l3 => l3.Parent == l2.Id)
                    .Select(l3 => new AllLevels
                    {
                        Id = l3.Id,
                        Desc = l3.Desc,
                        HasChild = false,
                        Children = new List<AllLevels>()
                    })
                })
            });