3

I have an array of Car objects

I want to conver them to a list of Vehicle objects

I thought this would work

Vehicle[] vehicles = cars.ConvertAll(car=> ConvertToVehicle(car)).ToArray();

but its complaining that ConvertAll requires two parameters.

here is the error:

Error 2 Using the generic method 'System.Array.ConvertAll(TInput[], System.Converter)' requires '2' type arguments C:\svncheckout\latestTrunk\Utility\test.cs 229 33

am i using the wrong method here?

leora
  • 188,729
  • 360
  • 878
  • 1,366

4 Answers4

4

You're using ConvertAll on an Array of cars (Car[]) instead of a List of cars (List) which does indeed require two type parameters1. If cars is a list your code will work.

Rodrick Chapman
  • 5,437
  • 2
  • 31
  • 32
  • i updated the question to note that i have an ARRAY (not a List). what is the best practice given that i have an array – leora Jun 28 '10 at 03:06
  • 1
    @ooo Array.ConvertAll(cars, c => ConvertToVehicle(car)); ConvertAll is a static method on the Array class. – Rodrick Chapman Jun 28 '10 at 03:16
1

That's a static function, written before extension methods were introduced, so you can't call it like a method.

Correct syntax:

Array.ConvertAll<Vehicle>(cars, car=> ConvertToVehicle(car))
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
1

While Array.ConvertAll pre-dates things like extension methods, your expected behaviour is exactly how Select works:

Vehicle[] vehicles = cars.Select(car=> ConvertToVehicle(car)).ToArray();

vs

Vehicle[] vehicles = Array.ConvertAll(cars, car=> ConvertToVehicle(car));

Differences:

  • Enumerable.Select, while static, is an extension method - so appears to be an instance method
  • Array.ConvertAll is static but isn't an extension method
  • Enumerable.Select returns an IEnumerable<T>, so you need Enumerable.ToArray to get an array
  • Array.ConvertAll returns an array already, and additionally ensures it is the right size much more efficiently than Enumerable.ToArray can
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

If Car is a Sub Type of Vehicle Super Type you can do the following.It should work equally well if ConvertToVehicle returns a Vehicle type.

class Vehicle { }
class Car : Vehicle { }

class Program
{
    static List<Car> ll = new List<Car>();
    static void Main(string[] args)
    {
       Vehicle[] v = ll.ConvertAll<Vehicle>(x => (Vehicle)x).ToArray();
    }
}
josephj1989
  • 9,509
  • 9
  • 48
  • 70