Array.ConvertAll method in C#
Posted On: 27-Mar-2016 12:39
Array.ConvertAll Converts an array of one type to an array of another type. Type can be primitive data type or user-defined data type as class and other complex data types.
In this Article we try to convert an array of user-defined data type like class to an array of another user-defined data type.
When use it
Suppose you have two array one is an array of string (String A) and another one an array of int (int B). And you want to convert from B to A.
In this case you can use Array.ConvertAll method.
Why use it
Probably faster since a fixed-size buffer is used. It simplifies the conversion by creating the array and doing the looping for you.
How use it
It has syntax as
Array.ConvertAll<TInput, TOutput> Method (TInput, Converter<TInput, TOutput>)
The one-dimensional, zero-based Array to convert to a target type.
Type: System.Converter<TInput, TOutput>
A Converter<TInput, TOutput> that converts each element from one type to another type.
An array of the target type containing the converted elements from the source array.
The type of the elements of the source array.
The type of the elements of the target array.
In the following example we have two class InputClass and OutputClass , one method ConvertArrayObject that will convert array of InputClass to array of OutputClass.
In the above discusion we try to understand when and how to use Array.ConvertAll method. I hope it will help you.