HomeCSharpHow to Convert String Array to Decimal Array in C# ?

How to Convert String Array to Decimal Array 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 .

How to convert Array from one type to another in C# ?

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&lt;string, double&gt;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

Leave a Reply

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...