C#是否支持“嵌套”程序,例如产生IEnumerable?

时间:2014-01-10 12:49:34

标签: c#

伪示例

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)
                })
         );

2 个答案:

答案 0 :(得分: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 :(得分:4)

不,它没有。它支持迭代器和匿名方法,但不支持匿名迭代器。请参阅this blog post by Eric Lippert

可能有另一种方法可以做你想要的,但是你发布的代码并没有真正意义......你想做什么?好的,我现在明白了......尤金的答案应该做你想要的。