2

I have the following code which transforms a List of myCar objects to an Array of Car objects from a third-party web service so I can then pass the cars to the 3rd party web service:

var cars = new Car[myCars.Count];
var count = 0;
foreach (var myCar in myCars)
{
   cars[count] = new Car
   {
      Id = myCar.Id,
      Manufacturer = myCar.Manufacturer,
      Model = myCar.Model
   };
   count++;
}
return cars;

Note as my myCar object has a number of other features other than the three the 3rd Party web service has I cant do something simple such as:

MyClass[] myArray = list.ToArray();

The code is working as expected but I am wondering is there something in Linq such as a Select expression which would make this better and take less code?

Brandon
  • 645
  • 5
  • 13
Ctrl_Alt_Defeat
  • 3,933
  • 12
  • 66
  • 116
  • 2
    [This post](http://stackoverflow.com/questions/19974013/convert-foreach-to-linq-statement-using-where) should help get you started. – Brandon May 28 '14 at 18:03
  • possible duplicate of [Change a list's property using linq](http://stackoverflow.com/questions/23691123/change-a-lists-property-using-linq) – TheNorthWes May 28 '14 at 18:07

2 Answers2

10
var cars = myCars.Select(myCar => new Car
{
    Id = myCar.Id,
    Manufacturer = myCar.Manufacturer,
    Model = myCar.Model
}).ToArray();
Jeremy Cook
  • 20,840
  • 9
  • 71
  • 77
3

The Select linq method lets you transform one object into another:

var cars = myCars.Select( c => new Car { id = c.Id, Manufacturer = c.Manufacturer, Model = c.Model } ).ToArray()

I think that will do it.

sircodesalot
  • 11,231
  • 8
  • 50
  • 83
Tony Vitabile
  • 8,298
  • 15
  • 67
  • 123