2011-01-31 62 views
10

如果我有一個SortedList<int, MyClass>,我想返回一個新的IEnumerable<T>屬性從那個類怎麼做?我試過SortedList.Select(x=>x.MyProperty, x.AnotherProperty)但它不起作用。使用Linq來選擇類的屬性返回IEnumerable <T>

謝謝。

+0

應該如何「無數的財產」呈現自己?你能給我們一個樣本,最好是用僞代碼嗎? – Ani 2011-01-31 12:28:44

回答

17

你可以返回一個匿名對象:

var result = SortedList.Select(x => new { 
    x.Value.MyProperty, 
    x.Value.AnotherProperty 
}); 

或者,如果你想使用的結果,當前方法的範圍之外,你可以定義一個自定義類型:

IEnumerable<MyType> result = SortedList.Select(x => new MyType { 
    Prop1 = x.Value.MyProperty, 
    Prop2 = x.Value.AnotherProperty 
}); 
+0

謝謝。當頭撞牆的時候,忘記了x =>新的{....... – Jon 2011-01-31 15:09:38

相關問題