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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1178891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:08:55  来源:igfitidea点击:

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

c#linqlambda

提问by David.Chu.ca

The question and answer of converting a class to another listof class is cool. How about to convert a list of MyData to another list of MyData2? For example:

将一个类转换为另一个列表的问答很酷。如何将 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 = ... ?

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 有一个像 (string, string, string) 这样的 CTOR。

采纳答案by Stan R.

If the two types are different, you would use the same Select to map to the new list.

如果两种类型不同,您将使用相同的 Select 来映射到新列表。

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

回答by Rob Elliott

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