2011-03-22 76 views
0

我刚刚发现我不流利与delegateaction和我想另外一个...使用委托的IEnumerable转换扩展函数?

我有一定的IEnumerable<T>,我想用委托功能转变为一个IEnumerable<object>那创建object作为匿名对象。 扩展方法会在这里派上用场,或者可能已经存在?

这个(或类似的东西)应该可以吧?

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

你不能使用Select - 'list.Select(x => return new {})'? – Martin 2011-03-22 14:00:51

回答

8

如果您使用.NET 4,你刚才所描述的方法Select

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

对于.NET 3.5你需要投你代表的结果,因为它没有通用的协方差:

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

或者使用隐式类型的局部变量,并得到一个强类型的序列:

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

太棒了,选择方法确实正是我所需要的! – Ropstah 2011-03-22 14:06:43

+0

下次回答我的问题之前5分钟,你介意等一下吗?一些程序员内置了一个5分钟的“接受应答延迟”......;) – Ropstah 2011-03-22 14:08:04