Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq query to return a flatened list of parent child

Tags:

c#

linq

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

like image 783
Chris Browne Avatar asked Nov 10 '08 11:11

Chris Browne


1 Answers

from parent in parents
from child in parent.Children
select new ParentChild() { ParentName = parent.Name, ChildName = child.Name };
like image 110
Kent Boogaart Avatar answered Sep 27 '22 21:09

Kent Boogaart