Linq查询返回父子关系扁平化列表

5

我对linq世界还很陌生,需要帮助将一个有子元素的父级列表平铺成一个单一的ParentChild列表。

就像这样:

class Program
{
    static void Main()
    {
        List<Parent> parents = new List<Parent>();

        parents.Add(new Parent { Name = "Parent1", Children = new List<Child> { new Child { Name = "Child1" }, new Child { Name = "Child2" } } });
        parents.Add(new Parent { Name = "Parent2", Children = new List<Child> { new Child { Name = "Child3" }, new Child { Name = "Child4" } } });

        // linq query to return List<ParentChild> parentChildList;
        // ParentName = Parent1, ChildName = Child1
        // ParentName = Parent1, ChildName = Child2
        // ParentName = Parent2, ChildName = Child3
        // ParentName = Parent2, ChildName = Child4
    }

    internal class ParentChild
    {
        public string ParentName { get; set; }
        public string ChildName { get; set; }
    }

    internal class Parent
    {
        public string Name { get; set; }
        public List<Child> Children { get; set; }
    }

    internal class Child
    {
        public string Name { get; set; }
    }
}

非常感谢,Chris。
2个回答

13
from parent in parents
from child in parent.Children
select new ParentChild() { ParentName = parent.Name, ChildName = child.Name };

我该如何将其绑定到Windows应用程序中的DataGridView?我尝试了"grdTerminals.DataBindings.Add("TerminalName", datasource, "Terminal")",但返回一个空字符串。 - Welsh King

3
这应该能为您解决问题:
var k = from p in parents
        from c in p.Children
        select new {Name = p.Name, Child = c.Name };

编辑:哎呀,忘记返回一个新的ParentChild对象了。但是肯特已经超过我了;)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接