Convert a String Array to a Decimal Array using C#

Question is...
Convert a String Array to a Decimal Array using C#

The Array.ConvertAll() method is a very useful method to convert an array of one type to an array of another type.

Here’s how to use ConvertAll() to convert a String[] to Decimal[]


static void Main(string[] args)
{
string[] strArray = new string[] { "1164", "2213" };

decimal d;
decimal[] d1;

// Check if string can be converted to decimal equivalent
if (strArray.All(number => Decimal.TryParse(number, out d)))
{
d1 = Array.ConvertAll<string, decimal>(strArray, Convert.ToDecimal);
}
}

The first step is to use Enumerable.All(TSource) to determine whether all the elements in a sequence satisfy a condition, in our case, if all the elements of the array can be converted to its decimal equivalent.

Once this can be done, we use ConvertAll() to convert an array of string to an array of decimal.

2 Responses so far.

  1. Stacyk says:
    This comment has been removed by the author.
  2. Stacyk says:

    thanks for this. Solved my problem.

Leave a Reply