2014-01-10 67 views
1

僞例如C#是否支持「嵌套」過程產生一個IEnumerable?

public HttpResponseMessage GetAll() { 

    List<MyEntity> before = MyEntityRepository.GetAll(); 
    return Request.CreateResponse(HttpStatusCode.OK, 
     new IEnumerable<MyExtendedEntity>({ 
      before.ForEach(x => 
       yield return new ExtendedEntity { 
        Property1 = x.Property1, 
        Property2 = x.Property2, 
        ExtendedProp = ExtendedPropProvider.getExtended(x) 
       }) 
     ); 

回答

12

對於你的例子,爲什麼不使用Select?

public HttpResponseMessage GetAll() { 

List<MyEntity> before = MyEntityRepository.GetAll(); 
return Request.CreateResponse(HttpStatusCode.OK, 
    before.Select(x => new ExtendedEntity 
    { 
     Property1 = x.Property1, 
     Property2 = x.Property2, 
     ExtendedProp = ExtendedPropProvider.getExtended(x) 
    })); 
+1

哇,爲什麼我沒有想過呢?簡單明瞭。謝謝。 – Acrotygma

4

不,不。它支持迭代器和匿名方法,但不支持匿名迭代器。請參閱this blog post by Eric Lippert

有可能是另一種方法來做你想做的事情,但你發佈的代碼沒有意義......你想做什麼? 好吧,我現在明白了...尤金的回答應該做你想做的。