开发者

IEnumerable transform extension function using delegate?

I just found out I'm not as fluent with delegate and action and the other one as I would want...

I have a certain IEnumerable<T> which I would like to transform to a IEnumerable<object> using a delegate function that creates object as an anonymous object. An e开发者_运维问答xtension method would come in handy here or might already exist?

This (or something like this) should be possible right?

IEnumerable<SomeBllObject> list;
IEnumerable<object> newList = list.Transform(x => return new {
                        someprop = x.SomeProp, 
                        otherprop = x.OtherProp
                  });


If you're using .NET 4, you've just described the Select method:

IEnumerable<object> newList = list.Select(x => new {
                        someprop = x.SomeProp, 
                        otherprop = x.OtherProp
                  });

For .NET 3.5 you'd need to cast the result of your delegate, as it doesn't have generic covariance:

IEnumerable<object> newList = list.Select(x => (object) new {
                        someprop = x.SomeProp, 
                        otherprop = x.OtherProp
                  });

Or use implicitly typed local variables and get a strongly typed sequence:

var newList = list.Select(x => new {
                        someprop = x.SomeProp, 
                        otherprop = x.OtherProp
                  });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜