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).
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;
}
);
list2 = list1.ConvertAll<MyData>( a => a.MyConversion() )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With