Array.ConvertAll
This C# method converts an entire array in a declarative statement. Each element in the source array is changed to another type.
We specify the conversion function—this can be done in the lambda expression syntax form. Any type conversion can be performed.
To begin, we create an integer array of 3 elements on the managed heap. Then, we invoke the Array.ConvertAll
static
method. The type parameters are inferred by the compiler.
Array.ConvertAll
is a lambda expression. The lambda returns the ToString()
method result on the element.using System; // Integer array of 3 values. int[] array1 = new int[3]; array1[0] = 4; array1[1] = 5; array1[2] = 6; // Use ConvertAll to convert integer array to string array. string[] array2 = Array.ConvertAll(array1, element => element.ToString()); // Write string array. Console.WriteLine(string.Join(",", array2));4,5,6
How does the Array.ConvertAll
method work? The lambda expression (the conversion function) is called each time an element is to be converted.
ConvertAll
method allocates a new array and then places the result of the converter method into each corresponding element slot.It would be faster to write an imperative method. This would eliminate the delegate method invocations and the overhead that occurs with argument checking.
The Array.ConvertAll
method allows you to declaratively convert an entire array with a single statement. It can simplify code, particularly when many conversions take place.