2013-03-29 165 views
0

如果我有一個包含10個屬性的對象列表,並且我想返回這些對象的列表,但只有10個可用的3個屬性,將如何我這樣做?僅返回對象的幾個屬性

public class Example 
{ 
    public int attr1 {get;set;} 
    public int attr2 {get;set;} 
    public int attr3 {get;set;} 
    public int attr4 {get;set;} 
    public int attr5 {get;set;} 
} 

return ExampleList; //have the return value be a list with only attr1, 2, and 3 visible. 
+0

http://msdn.microsoft.com/en-us/library/vstudio/bb397696.aspx –

回答

4

您可以使用LINQ與Select方法並返回anonymous type

var result = ExampleList.Select(x => new { x.attr1, x.attr2, x.attr3 }); 

或者,明確用3個屬性定義自己的類,這種情況下,通常,如果你從域實體轉換爲視圖模型或DTO對象:

class Dto 
{ 
    public int Pro1 { get; set; } 
    public int Pro2 { get; set; } 
    public int Pro3 { get; set; } 
} 

var result = ExampleList.Select(x => new Dto { 
             Pro1 = x.attr1, 
             Pro2 = x.attr2, 
             Pro3 = x.attr3 
            }); 

或者,如果你只是想要一個轉儲類,你可以使用Tuple

var result = ExampleList.Select(x => Tuple.Create(x.attr1, x.attr2, x.attr3)); 
+0

+1是第一個發佈這個答案 –

+0

這是我正在尋找,但爲什麼,在第一個例子(匿名類型的例子)我得到「類型參數不能從使用推斷」錯誤? – proseidon

+0

@ proseidon:我編輯了我的答案 –

0

使屬性可以爲空並使用Object Initializers

public class Example 
{ 
    public int? attr1 {get;set;} 
    public int? attr2 {get;set;} 
    public int? attr3 {get;set;} 
    public int? attr4 {get;set;} 
    public int? attr5 {get;set;} 
} 
0

使用LINQ投影算:

var resultList = ExampleList.Select(x => new 
    { 
     x.attr1, 
     x.attr2, 
     x.attr3 
    }); 

或者,如果你需要指定另一名道具:

var resultList = ExampleList.Select(x => new 
    { 
     PropName1 = x.attr1, 
     PropName2 = x.attr2, 
     PropName2 = x.attr3, // <- The last comma can be leaved here. 
    }); 
是導致枚舉

注意的是Example型不能不預先的編譯(不是運行時)創建的匿名類型。