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

标签 c# linq lambda

converting a class to another list的问答类很酷。如何将 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。

最佳答案

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

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

编辑添加:

既然你改变了你的问题。你可以做这样的事情来修复你想要做的事情。

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

关于c# - 使用 Lambda 或 LINQ 将一个类列表转换或映射到另一个类列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1178891/

相关文章:

c# - 错误: Inserting a BLOB in MySQL results in null using C#

c# - 抑制或避免警告 CA2214

linq - NHibernate.Linq 和 MultiCriteria

java - 为什么比较器声明等于?

Java Streams 将 EnumMap 的 Map 转换为列表的 Map

c# - 从 silverlight 富文本框中提取纯文本 - LINQ to XML

c# - 正则表达式替换多个组

sql - Entity Framework (LINQ) 可以根据 JSON where 子句选择行吗?

c# - 如何使用 Linq 按日期对订单列表进行分组

node.js - Lambda 函数测试永远不会通过