tags:

views:

259

answers:

2

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

+4  A: 

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;
       }
      );
Stan R.
I updated my codes, partial one. This case, I have to take consideration of PropertyList is null or not. How to map there?
David.Chu.ca
I like this. By the way, in my partial codes, I tried to use Union and I got it working by using <a href="http://stackoverflow.com/questions/1178891/convert-or-map-a-list-of-class-to-another-list-of-class-by-using-lambda-or-linq/1178924#1178924">Rob Elliott</a>. What's difference between Aggregate and Union?
David.Chu.ca
+1  A: 
list2 = list1.ConvertAll<MyData>( a => a.MyConversion() )
Rob Elliott
how about detail inline Lambda expression for MyConversion()?
David.Chu.ca
I see your point. MyConversion() is a method defined in MyData2 class.
David.Chu.ca
actually, ConvertAll is not working. I use list1.SelectMany(..).ToList() and no compile error. Is that right?
David.Chu.ca
Use what works! Though ConvertAll should also work.
Rob Elliott
SelectMany() is working or compiling error, but when I tried ConverAll(), I got compiling error. The problem is that I need to get a list of MyData from a.MyConversion() since a.PropertyList contains more than one value.
David.Chu.ca
I mean SelectMany() without compiling error. Sorry for typo.
David.Chu.ca