Csharp/C#教程:使用Lambda或LINQ将类列表转换或映射到另一个类列表?分享


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

将类转换为另一个类列表的问题和答案很酷。 如何将MyData列表转换为另一个MyData2列表? 例如:

List list1 = new List(); // somewhere list1 is populated List 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有一个CTOR(字符串,字符串,字符串)。

如果两种类型不同,您可以使用相同的选择映射到新列表。

 list2 = list1.Select( x => new MyData2() { //do your variable mapping here PropertyB = x.PropertyB, PropertyC = x.PropertyC } ).ToList(); 

编辑添加

现在你改变了你的问题。 你可以做这样的事情来解决你想要做的事情。

上述就是C#学习教程:使用Lambda或LINQ将类列表转换或映射到另一个类列表?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 list2 = list1.Aggregate(new List(), (x, y) => { if (y.PropertyList == null) x.Add(new MyData2(null, y.PropertyB, y.PropertyC)); else x.AddRange(y.PropertyList.Select(z => new MyData2(z, y.PropertyB, y.PropertyC))); return x; } ); 

 list2 = list1.ConvertAll( a => a.MyConversion() ) 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1008573.html

(0)
上一篇 2021年12月29日
下一篇 2021年12月29日

精彩推荐