通过使用Lambda或LINQ将类实例转换或映射到另一个实例的列表? [英] Convert or map a class instance to a list of another one by using Lambda or LINQ?

查看:72
本文介绍了通过使用Lambda或LINQ将类实例转换或映射到另一个实例的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两个课程:

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; }
}

如果我有MyClass的实例,则需要将其转换为MyData2的列表.我可以通过循环MyData.PropertyList并缓存其他属性值并将其插入到MyData2列表中来做到这一点,就像这样:

If I have an instance of MyClass, I need to convert it to a list of MyData2. I could do it by looping MyData.PropertyList and caching other property values and inserting them to a list of MyData2 like this:

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 });
}

不确定使用LINQ或Lambda表达式的.Net 3.5功能是否可以实现?

Not sure if this can be done with .Net 3.5 features of LINQ or Lambda expression?

推荐答案

简单易用.您要基于特定列表中的每个项目(字符串)来执行某项操作,因此应将其作为查询表达式的起点.您要为每个字符串创建一个新项目(a MyData2),因此您要使用投影.您想在最后创建一个列表,因此您调用ToList()完成该工作:

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();

这篇关于通过使用Lambda或LINQ将类实例转换或映射到另一个实例的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆