Using Array.ConvertAll to Convert an array of one type to another in C#

Thanks to one of My friend (Anil pai) , who asked me a question on how to convert a string array to an float/Double Array which made me to explore the  possibilities in .NET and this is when i came across Array.ConvertAll

The usual way of doing this is to parse and convert each values one by one like this

string[] sArray = new string[]{"1","3"};
decimal[] dArray = new decimal[2];
for (int i=0; i < sArray.Length; i++)
{
    dArray[i] = Convert.ToDecimal(sArray[i]);
}

Now , Array.ConvertAll makes the things easier for us .

You can use Array.ConvertAll method to convert an array of one type to an array of another.

This method is found in the namespace – System and the assembly mscorlib.dll .

The first parameter is the input array and the second parameter is the Converter which represents a delegate method that converts an object from one type to another type. .

public static void Main()
{
string[] sArray = new string[]{"1","3"};
decimal[] dArray = Array.ConvertAll<string, double>sArray,Convert.ToDouble);
}

This will help simplify the code especially when there are many different conversions in the program .

This method is supported in the following .NET framework

  • .NET 4.0
  • .NET 3.5
  • .NET 3.0
  • .NET 2.0
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

No Responses

  1. Using Array.ConvertAll to Convert an array of one type to another in C# | ProgramInDotnet August 9, 2011 Reply

Leave a Reply


x

Interesting BlogPosts to read

How to get an Enumerator from range of elements from ArrayList in C# ?
The code snippet shown in this blog post demonstrates how you can get the enumeraor from a range of ...
How to check for the column name in an SqlDataReader Object in C# ?
When working in ADO.NET for data access , there are times when you want to check to see if a column ...
How to convert Array to List in C#?
Want to convert array of strings to List of strings in C# ? . Below is a sample code to illustrate t...