[英]Linq query to return a flatened list of parent child
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. 对于linq的世界来说还是新手,我需要一些帮助,将有孩子的父母列表整理成一个ParentChild列表。
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 };
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. 编辑:Opps忘记返回一个新的ParentChild对象。 but Kent beat me to it ;)
但肯特打败了我;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.