tags:

views:

1350

answers:

3

Hi all, 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

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

HTH, Kent

Kent Boogaart
+2  A: 

This should do it for you:

var k = from p in parents
        from c in p.Children
        select new {Name = p.Name, Child = c.Name };

EDIT: Opps forgot to return a new ParentChild object. but Kent beat me to it ;)

Nathan W
A: 

Thanks Kent, that helped a lot :)

Chris Browne