对 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; }
}
}
非常感谢,
克里斯
from parent in parents
from child in parent.Children
select new ParentChild() { ParentName = parent.Name, ChildName = child.Name };
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)