有没有一种 LINQ 方法可以做到这一点?任何帮助是极大的赞赏。
class Program
{
static void Main(string[] args)
{
Parent parent1 = new Parent();
parent1.Name = "P1";
Parent parent2 = new Parent();
parent2.Name = "P2";
Child child1 = new Child();
child1.Name = "C1";
Child child2 = new Child();
child2.Name = "C2";
Child child3 = new Child();
child3.Name = "C3";
Child child4 = new Child();
child4.Name = "C4";
parent1.Children.Add(child1);
parent1.Children.Add(child2);
parent2.Children.Add(child3);
parent2.Children.Add(child4);
List<Parent> parentCollection = new List<Parent>();
parentCollection.Add(parent1);
parentCollection.Add(parent2);
List<string> nameCollection = new List<string>();
foreach( Parent parent in parentCollection){
nameCollection.Add(parent.Name);
foreach(Child child in parent.Children)
nameCollection.Add(child.Name);
}
}
}
public class Parent
{
public string Name = string.Empty;
public List<Child> Children = new List<Child>();
}
public class Child
{
public string Name = string.Empty;
}