2011-03-22 38 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