使用 Lambda 或 LINQ 将一个类列表转换或映射到另一个类列表?
将一个类转换为另一个类列表 很酷。 如何将一个 MyData 列表转换为另一个 MyData2 列表? 例如:
List<MyData> list1 = new List<MyData>();
// somewhere list1 is populated
List<MyData2> list2;
// Now I need list2 from list1. How to use similar LINQ or Lambda to get
list2 = ... ?
在这里我尝试了这个,但我无法弄清楚完整的代码:
list2 = (from x in list1 where list1.PropertyList == null
select new MyData2( null, x.PropertyB, x.PropertyC).
Union (
from y in list1 where list.PropertyList != null
select new MyData2( /* ? how to loop each item in ProperyList */
y.PropertyB, y.PropertyC)
).ToList();
其中 MyData2 有一个类似 (string, string, string) 的 CTOR。
The question and answer of converting a class to another list of class is cool. How about to convert a list of MyData to another list of MyData2? For example:
List<MyData> list1 = new List<MyData>();
// somewhere list1 is populated
List<MyData2> list2;
// Now I need list2 from list1. How to use similar LINQ or Lambda to get
list2 = ... ?
Here I tried this but I cannot figure out the complete codes:
list2 = (from x in list1 where list1.PropertyList == null
select new MyData2( null, x.PropertyB, x.PropertyC).
Union (
from y in list1 where list.PropertyList != null
select new MyData2( /* ? how to loop each item in ProperyList */
y.PropertyB, y.PropertyC)
).ToList();
where MyData2 has a CTOR like (string, string, string).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果两种类型不同,您将使用相同的 Select 来映射到新列表。
编辑添加:
现在您更改了问题。 您可以做这样的事情来解决您想要做的事情。
If the two types are different, you would use the same Select to map to the new list.
EDIT TO ADD:
Now that you changed your question. You can do something like this to fix what you're trying to do.