0
이렇게하려면 LINQ 방법이 있습니까? 어떤 도움이라도 대단히 감사합니다.linq을 사용하여 부모 - 자식 속성 병합
var all = parentCollection.Select(p=>p.Name)
.Concat(parentCollection
.SelectMany(p=>p.Children).Select(c=>c.Name));
참고이는 부모/자식 관계의 하나의 깊이와 함께 작동합니다 :
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;
}
코드 좋은 일이다. 재귀에 대해 언급하는 것이 이상합니다 - 나는 그것에 동의하지 않습니다. –
그래, 내가 좀 망쳤다. foo가 ienumerable 인 곳에서 "yield return foo"를 얻는 데 어려움이 있는지 생각했습니다. 여러 레벨이있는 경우 부모 자식 트리를 탐색하려면 사용자 지정 반복기를 통과해야합니다. –