2008-11-10 60 views
5

對於linq的世界來說還是一個新東西,我需要一些幫助將有孩子的父母的列表變成一個幫助列表到ParentChild的列表中。Linq查詢返回父親孩子的一張扁平化列表

就像這樣:

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

非常感謝, 克里斯

回答

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

我將如何去綁定到一個Windows應用程序中的DataGridView,我試過grdTerminals.DataBindings.Add(「TerminalName」,datasource,「Terminal」);但是這會返回一個空字符串 – 2012-11-26 16:27:42

3

這應該爲你做它:

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

編輯:哎呀忘記返回一個新的父子目的。但肯特擊敗了我;)