转换或使用拉姆达或LINQ类的列表映射到另一个类的列表? [英] Convert or map a list of class to another list of class by using Lambda or LINQ?

查看:98
本文介绍了转换或使用拉姆达或LINQ类的列表映射到另一个类的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题和的一类转换为另一个类的列表是很酷。怎么样对迈德特的列表转换为MyData2的另一个列表?例如:

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? 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();

其中MyData2有像(字符串CTOR,字符串,字符串)。

where MyData2 has a CTOR like (string, string, string).

推荐答案

如果这两种类型的不同,你会用同样的选择映射到新名单。

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



编辑补充

现在,你改变了你的问题。你可以做这样的事情来修复你想要做什么。

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

这篇关于转换或使用拉姆达或LINQ类的列表映射到另一个类的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆