Array.ConvertAll, Change Type of Elements
This page was last reviewed on Oct 3, 2023.
Dot Net Perls
Array.ConvertAll. This C# method converts an entire array in a declarative statement. Each element in the source array is changed to another type.
Lambda argument. 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.
Info The second argument to 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));
Internals. How does the Array.ConvertAll method work? The lambda expression (the conversion function) is called each time an element is to be converted.
Note The ConvertAll method allocates a new array and then places the result of the converter method into each corresponding element slot.
Performance notes. It would be faster to write an imperative method. This would eliminate the delegate method invocations and the overhead that occurs with argument checking.
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 3, 2023 (edit).
© 2007-2024 Sam Allen.