Array.ConvertAll method in C#

Views: 990
Comments: 1
Like/Unlike: 3
Posted On: 27-Mar-2016 12:39 

Share:   fb twitter linkedin
NiceOne...
Admin
40 Points
12 Posts

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.

public class InputClass {
public int id { get; set; }
public string name { get; set; }
}
public class OutputClass {
public string myId { get; set; }
public string myName { get; set; }
}
public OutputClass[] ConvertArrayObject(InputClass[] inputArray) {
return
System.Array.ConvertAll<InputClass, OutputClass>(inputArray, (elem) => {
return new OutputClass {
myId = elem.id.ToString(),
myName = elem.name
};
});
}

Conclusion

In the above discusion we try to understand when and how to use Array.ConvertAll method. I hope it will help you.

 

1 Comments

Priya
great...
  
banner

Blog

Active User (2)

 Log In to Chat