LINQ查询返回母儿的flatened名单 [英] Linq query to return a flatened list of parent child

查看:107
本文介绍了LINQ查询返回母儿的flatened名单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

还是新的LINQ的世界,我需要一些帮助flatening有孩子,到ParentChild的单一列表家长的名单。



就这样

 类节目
{
静态无效的主要()
{
清单<家长和GT;父母=新的List<家长和GT;();

parents.Add(新父{名称=Parent1,儿童=新的List<儿童> {新的儿童{名称=Child1},新的儿童{名称=CHILD2}}} );
parents.Add(新父{名称=Parent2,儿童=新的List<儿童> {新的儿童{名称=Child3},新的儿童{名称=Child4}}});

// LINQ查询返回列表< ParentChild> parentChildList;
// ParentName = Parent1,ChildName = Child1
// ParentName = Parent1,ChildName = CHILD2
// ParentName = Parent2,ChildName = Child3
// ParentName = Parent2,ChildName = Child4
}

内部类ParentChild
{
公共字符串ParentName {搞定;组; }
公共字符串ChildName {搞定;组; }
}

内部类父
{
公共字符串名称{;组; }
公开名单<儿童>儿童{搞定;组; }
}

内部类儿童
{
公共字符串名称{;组; }
}
}



非常感谢,
克里斯 -


解决方案

 从父母父从孩子parent.Children 

选择新ParentChild(){ParentName = parent.Name,ChildName = child.Name};


still new to the world of linq, and i need some help flatening a list of parents that have children, into a single list of ParentChild's.

Just like this:

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; }
    }
}

Many thanks, Chris

解决方案

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

这篇关于LINQ查询返回母儿的flatened名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆