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

I have the following two classes:

class MyData { public List<string> PropertyList { get; private set;} public string PropertyB { get; set; } public string PropertyC { get; set; } } class MyData2 { public string PropertyA { get; set;} public string PropertyB { get; set; } public string PropertyC { get; set; } } 

If I have an instance of MyClass, I need to convert it to a MyData2 list. I could do this by looping MyData.PropertyList and caching the other property values โ€‹โ€‹and entering them into the MyData2 list as follows:

 string propertyB = myData.PropertyB; string propertyC = myData.PropertyC; List<MyData2> myData2List = new List<MyData>(); foreach(string item in myData.PropertyList) { myData2List.Add(new myData2() { item, propertyB, propertyC }); } 

Not sure if this can be done with .Net 3.5 LINQ or Lambda expression functions?

+3
c # lambda linq
Jul 24. '09 at 6:29
source share
1 answer

It is nice and easy. You want to do something based on each item (string) in a specific list, so make this the starting point of the query expression. You want to create a new element (a MyData2 ) for each of these lines in order to use projection. You want to create a list at the end, so you call ToList() to complete the job:

  var myData2List = myData.PropertyList .Select(x => new MyData2 { PropertyA = x, PropertyB = myData.PropertyB, PropertyC = myData.PropertyC }) .ToList(); 
+13
Jul 24 '09 at 6:31
source share



All Articles