Array.ConvertAll method in C#
Introduction
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>)
Where
array
Type: TInput[]
The one-dimensional, zero-based Array to convert to a target type.
converter
Type: System.Converter<TInput, TOutput>
A Converter<TInput, TOutput> that converts each element from one type to another type.
Return Value
Type: TOutput[]
An array of the target type containing the converted elements from the source array.
Type Parameters
TInput
The type of the elements of the source array.
TOutput
The type of the elements of the target array.
Example
In the following example we have two class InputClass and OutputClass , one method ConvertArrayObject that will convert array of InputClass to array of OutputClass.
Conclusion
In the above discusion we try to understand when and how to use Array.ConvertAll method. I hope it will help you.
Priya
05-May-2018 at 22:22