2014-04-20 2 views
0

나는 다음과 같은 클래스가 :고급 수집

class Word { } 
class Sentence: List<Word> { } 
class TextSection: List<Sentence> { } 
class TextBase: List<TextSection> { } 

을 그리고 나는 그것이 foreach 사용과 반복, 즉 Word의의 모음 인 것처럼 TextBase와 함께 작동 할 수 있도록하려면 SelectAggregate 방법.

이러한 모든 클래스에는 중요한 추가 필드와 메서드가 있으므로 TextBase: List<Word>으로 바꾸는 것은 옵션이 아닙니다.

가장 좋은 방법은 무엇입니까?

UPD : IEnumerable<Word>을 구현하면 내 문제가 해결되지만 TextBase.Where()을 호출하면 IEnumerable<Word>이 반환됩니다. 내 기본 구문을 문장으로 파손시킬 수 있습니다.이를 피할 수 있습니까?

+1

확인이 http://stackoverflow.com/questions/9455043/how-do-i-make-a-class-iterable – hgulyan

+0

@ user3554721 당신이 '목록에 TextBase'을 평평하게 할 것을 의미 할 '단어'? – dkozl

+0

@hgulyan 감사합니다. 그러나 UPD를보십시오. – 0x60

답변

0

당신은 TextBase에 IEnumerable을 구현할 수 있습니다

class TextBase: List<TextSection>, IEnumerable<Word> 
{  
    IEnumerator<Word> IEnumerable<Word>.GetEnumerator() 
    { 
     return ((List<TextSection>)this).SelectMany(c => c.SelectMany(w => w)).GetEnumerator(); 
    } 
} 
+0

나는'return ((List ) this) .SelectMany (ts => ts.SelectMany (s => s)). GetEnumerator();' –

+0

네. 고맙습니다. –

1

당신이 TextBase 구현이있는 경우 모두 IEnumerable<TextSection> 당신이 유형을 지정해야합니다 때문에 LINQ와 함께 작동하는 고통을 될 것입니다 (목록을 통해) 및 IEnumerable<Word>WhereSelect과 같은 모든 LINQ 메서드. 단어를 반복 할 수있는 Words과 같은 속성을 만드는 것이 가장 좋습니다. 같은

뭔가 :

class TextBase : List<TextSection> 
{ 
    public IEnumerable<Word> Words 
    { 
     get { return this.SelectMany(s => s.Words); } 
    } 
} 

class TextSection : List<Sentence> 
{ 
    public IEnumerable<Word> Words 
    { 
     get { return this.SelectMany(s => s); } 
    } 
} 
-2

가 왜 속성을 추가?

public IEnumerable<Word> Words 
    { 
     get 
     { 
      // return all words somehow, maybe using yield 
     } 
    } 
+0

그와 같은 답변이 40 분 전에있었습니다. –