Convert or map a class instance to a list of another one by using Lambda or LINQ?

前端 未结 1 740
长发绾君心
长发绾君心 2021-01-14 08:13

I have the following two classes:

class MyData {
  public List PropertyList { get; private set;}
  public string PropertyB { get; set; }
  publ         


        
1条回答
  •  梦毁少年i
    2021-01-14 08:46

    It's nice and easy. You want to do something based on every item (a string) in a particular list, so make that the starting point of your query expression. You want to create a new item (a MyData2) for each of those strings, so you use a projection. You want to create a list at the end, so you call ToList() to finish the job:

     var myData2List = myData.PropertyList
                             .Select(x => new MyData2 { 
                                 PropertyA = x, 
                                 PropertyB = myData.PropertyB, 
                                 PropertyC = myData.PropertyC })
                             .ToList();
    

    0 讨论(0)
提交回复
热议问题