Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

lambda

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? 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).

like image 622
David.Chu.ca Avatar asked Jul 24 '09 16:07

David.Chu.ca


2 Answers

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;
                }
            );
like image 110
Stan R. Avatar answered Oct 31 '22 09:10

Stan R.


list2 = list1.ConvertAll<MyData>( a => a.MyConversion() )
like image 7
Rob Elliott Avatar answered Oct 31 '22 09:10

Rob Elliott