2011-09-30 50 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