【问题标题】:Merge parent-child property using linq使用 linq 合并父子属性
【发布时间】:2009-06-02 05:29:09
【问题描述】:

有没有 LINQ 方法来完成这个?非常感谢任何帮助。

class Program
{
    static void Main(string[] args)
    {
        Parent parent1 = new Parent();
        parent1.Name = "P1";


        Parent parent2 = new Parent();
        parent2.Name = "P2";


        Child child1 = new Child();
        child1.Name = "C1";

        Child child2 = new Child();
        child2.Name = "C2";

        Child child3 = new Child();
        child3.Name = "C3";

        Child child4 = new Child();
        child4.Name = "C4";


        parent1.Children.Add(child1);
        parent1.Children.Add(child2);


        parent2.Children.Add(child3);
        parent2.Children.Add(child4);

        List<Parent> parentCollection = new List<Parent>();
        parentCollection.Add(parent1);
        parentCollection.Add(parent2);



        List<string> nameCollection = new List<string>();


        foreach( Parent parent in parentCollection){
            nameCollection.Add(parent.Name);
            foreach(Child child in parent.Children)
                nameCollection.Add(child.Name);

        }

    }
}


public class Parent
{
    public string Name = string.Empty;
    public List<Child> Children = new List<Child>();
}
public class Child
{
    public string Name = string.Empty;
}

【问题讨论】:

    标签: linq parent


    【解决方案1】:

    您可以使用 SelectMany 来展平子集合:

    var all = parentCollection.Select(p=>p.Name)
            .Concat(parentCollection
                        .SelectMany(p=>p.Children).Select(c=>c.Name));
    

    请注意,这只适用于一种深度的父/子关系。你有真正的递归(几个级别),你必须实现一个迭代器,递归地产生子节点。

    编辑:让孩子按正确的顺序排列,一些丑陋的东西:

        var all = parentCollection.Select(p=>new {Parent=p.Name, Name = ""})
                .Concat(parentCollection.SelectMany(p=>p.Children
                                .Select(c => new {Parent=p.Name, c.Name})))
                .OrderBy(o => o.Parent).ThenBy(o => o.Name)
                .Select(o=> o.Name != "" ? o.Name : o.Parent);
    

    【讨论】:

    • 代码不错+1。关于递归的评论很奇怪 - 我不同意。
    • 是的,我确实有点搞砸了。我正在考虑在 foo 是可枚举的情况下获得“yield return foo”的困难。如果有多个级别,您必须通过自定义迭代器来遍历父子树。
    猜你喜欢
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多