2012-10-19 7 views
1

를 동작하지 않습니다 계층 구조.나는 모든 자식 개체를 반환하려면 어떻게 - 나는 SelectMany 내가 대신,</p> <pre><code>public class Foo { public IList<Foo> Items { get; set; } } public class FooList { public IList<Foo> Items { get; set; } } </code></pre> <p>내가 푸 모두가 하나의 목록에서 개체를 얻을 수있을하고자하는 클래스가

나는

IEnumerable<Foo> result = Items.SelectMany(f => f.Items); 

을 시도했지만이 그냥 특정 개체 나에게 항목을 얻는다 - 그것은 모든 자식 개체에있는 모든 항목을하지 않습니다.

는 또한

IEnumerable<Foo> result = Items.SelectMany(t => t) 

을 시도하지만 오류 얻을 : 당신이 fooList라는 FooList 인스턴스가 있다고 가정

The type arguments for method 'System.Linq.Enumerable.SelectMany(System.Collections.Generic.IEnumerable, System.Func>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

+0

FooList에는 foos 목록이 있습니다. 각 Foo에는 또한 foos 목록이 있으며, 각 foos에는 foos 목록이 있습니다. – rozza

답변

0

부르는 "평평-이 트리"당신이 더 일반적인 경우에 사용할 수있는 LINQ와 같은 기능 : 다음

public static IEnumerable<T> Flatten<T>(
    this IEnumerable<T> source, 
    Func<T, IEnumerable<T>> childSelector) 
{ 
    HashSet<T> added = new HashSet<T>(); 
    Queue<T> queue = new Queue<T>(); 
    foreach(T t in source) 
     if (added.Add(t)) 
      queue.Enqueue(t); 
    while (queue.Count > 0) 
    { 
     T current = queue.Dequeue(); 
     yield return current; 
     if (current != null) 
     { 
      IEnumerable<T> children = childSelector(current); 
      if (children != null) 
       foreach(T t in childSelector(current)) 
        if (added.Add(t)) 
         queue.Enqueue(t); 
     } 
    } 
} 

을 당신이 FooList이있는 경우, 당신은

var allFoos = myFooList.Items.Flatten(foo => foo.Items); 

목록에있는 모든 Foo들하는데 사용할 수있는, 모든 아이들과 함께 아이들과 ...

+0

그것은 훌륭합니다 - 고마워요! – rozza

0

을 :

당신이 좋아하는 방법을 정의해야합니다 FooList 클래스의 경우 :

public IEnumerable<Foo> GetRecursiveFoos() 
{ 
    return Items.Concat(Items.SelectMany(x => x.Items)); 
} 

다음이 함께 노크 상당히 쉽게

IEnumerable<Foo> result = fooList.GetRecursiveFoos(); 
+0

이것은 실제로 재발하지 않습니다. 최상위 레벨과 하나의 레벨을 얻습니다. – Rawling

+0

@Rawling Right. 코드를 읽을 때 실수로 데이터 구조에 잘못된 인상을 받았습니다. – GolfWolf

관련 문제

 관련 문제