【问题标题】:Use linq to make a projection of an anonymous class with a list使用 linq 对带有列表的匿名类进行投影
【发布时间】:2011-09-30 19:12:41
【问题描述】:

假设我有这些课程:

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 来制作一个只有 Property1 和 Property2 的投影以及一个只有 SecondProperty4 和 SecondProperty5 的列表?

类似:

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

注意:只是为了澄清 myClass 是一个List&lt;MyClass&gt; 对象。

【问题讨论】:

    标签: c# linq projection


    【解决方案1】:
    myClass.Select(x=> new { Property1 = x.Property1, 
                             Property2 = x.Property2, 
                             SecondList = x.MyList.Select(i => new { i.SecondProperty4, i.SecondProperty5 }).ToList()
                           }
    

    【讨论】:

    • 我没有意识到这一点而感到愚蠢!感谢您的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多