简体   繁体   English

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

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

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? 如何将MyData列表转换为另一个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). 其中MyData2有一个CTOR(字符串,字符串,字符串)。

If the two types are different, you would use the same Select to map to the new list. 如果两种类型不同,您可以使用相同的选择映射到新列表。

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

EDIT TO ADD : 编辑添加

Now that you changed your question. 现在你改变了你的问题。 You can do something like this to fix what you're trying to do. 你可以做这样的事情来解决你想要做的事情。

list2 = list1.Aggregate(new List<MyData2>(),
                 (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<MyData>( a => a.MyConversion() )

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

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