2011-09-30 83 views
2

假設我有這些類:使用LINQ做一個匿名類的投影與列表

public MyClass 
{ 
    public Property1 {get; set;} 
    public Property2 {get; set;} 
    public Property3 {get; set;} 
    public Property4 {get; set;} 
    public Property5 {get; set;} 
    public Property6 {get; set;} 
    public Property7 {get; set;} 
    public Property8 {get; set;} 
    public List<MySecondClass> MyList {get; set;} 
} 

public MySecondClass 
{ 
    public SecondProperty1 {get; set;} 
    public SecondProperty2 {get; set;} 
    public SecondProperty3 {get; set;} 
    public SecondProperty4 {get; set;} 
    public SecondProperty5 {get; set;} 
} 

假設一切都被實例化,我將如何使用LINQ進行投影,僅僅有Property1Property2以及剛剛擁有SecondProperty4SecondProperty5的列表?

喜歡的東西:

myClass.Select(x=> new { Property1 = x.Property1, 
         Property2 = x.Property2, 
         //Some Way To add The list here 
         } 

注:只是爲了澄清myClass的是List<MyClass>對象。

回答

9
myClass.Select(x=> new { Property1 = x.Property1, 
         Property2 = x.Property2, 
         SecondList = x.MyList.Select(i => new { i.SecondProperty4, i.SecondProperty5 }).ToList() 
         } 
+0

我覺得啞巴沒有意識到!感謝你的回答。 – Vaccano