【问题标题】:Convert or map a list of class to another list of class by using Lambda or LINQ?使用 Lambda 或 LINQ 将一个类列表转换或映射到另一个类列表?
【发布时间】:2010-11-13 19:32:32
【问题描述】:

课堂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。

【问题讨论】:

    标签: c# linq lambda


    【解决方案1】:

    如果两种类型不同,您将使用相同的 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;
                    }
                );
    

    【讨论】:

    • 我更新了我的代码,部分代码。这种情况下,我不得不考虑 PropertyList 是否为空。如何映射到那里?
    • 我喜欢这个。顺便说一句,在我的部分代码中,我尝试使用 Union 并通过使用 stackoverflow.com/questions/1178891/…Elliott 使其工作。Aggregate 和 Union 有什么区别?
    【解决方案2】:
    list2 = list1.ConvertAll<MyData>( a => a.MyConversion() )
    

    【讨论】:

    • MyConversion() 的详细内联 Lambda 表达式怎么样?
    • 我明白你的意思。 MyConversion() 是 MyData2 类中定义的方法。
    • 实际上,ConvertAll 不起作用。我使用 list1.SelectMany(..).ToList() 并且没有编译错误。对吗?
    • SelectMany() 正在工作或编译错误,但是当我尝试 ConverAll() 时,出现编译错误。问题是我需要从 a.MyConversion() 获取 MyData 列表,因为 a.PropertyList 包含多个值。
    猜你喜欢
    • 2010-11-13
    • 1970-01-01
    • 2020-02-12
    • 1970-01-01
    • 2011-04-10
    • 1970-01-01
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多