tags:

views:

249

answers:

1

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 list of MyData2. I could do it by looping MyData.PropertyList and caching other property values and inserting them to a list of MyData2 like this:

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 features of LINQ or Lambda expression?

+8  A: 

It's nice and easy. You want to do something based on every item (a string) in a particular list, so make that the starting point of your query expression. You want to create a new item (a MyData2) for each of those strings, so you use a projection. You want to create a list at the end, so you call ToList() to finish the job:

 var myData2List = myData.PropertyList
                         .Select(x => new MyData2 { 
                             PropertyA = x, 
                             PropertyB = myData.PropertyB, 
                             PropertyC = myData.PropertyC })
                         .ToList();
Jon Skeet
how about the case myDataList is a list of myData? For example from myDataList to myData2List?
David.Chu.ca