简体   繁体   English

使用Lambda或LINQ将类实例转换或映射到另一个实例的列表?

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

I have the following two classes: 我有以下两个类:

class MyData {
  public List<string> PropertyList { get; private set;}
  public string PropertyB { get; set; }
  public string PropertyC { get; set; }
}

class MyData2 {
  public string PropertyA { get; set;}
  public string PropertyB { get; set; }
  public string PropertyC { get; set; }
}

If I have an instance of MyClass, I need to convert it to a list of MyData2. 如果我有一个MyClass实例,我需要将其转换为MyData2列表。 I could do it by looping MyData.PropertyList and caching other property values and inserting them to a list of MyData2 like this: 我可以通过循环MyData.PropertyList并缓存其他属性值并将它们插入MyData2列表来实现,如下所示:

string propertyB = myData.PropertyB;
string propertyC = myData.PropertyC;
List<MyData2> myData2List = new List<MyData>();
foreach(string item in myData.PropertyList)
{
  myData2List.Add(new myData2() { item, propertyB, propertyC });
}

Not sure if this can be done with .Net 3.5 features of LINQ or Lambda expression? 不确定是否可以使用LINQ或Lambda表达式的.Net 3.5功能完成此操作?

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. 您想为每个字符串创建一个新项目( MyData2 ),因此您可以使用投影。 You want to create a list at the end, so you call ToList() to finish the job: 您想在最后创建一个列表,因此您可以调用ToList()来完成作业:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM