Convert a String Array to a Decimal Array using C# or VB.NET

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[]

C#

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);
}
}

VB.NET

Sub Main(ByVal args() As String)
Dim strArray() As String = { "1164", "2213" }
Dim d As Decimal
Dim
d1() As Decimal
' Check if string can be converted to decimal equivalent
If strArray.All(Function(number) Decimal.TryParse(number, d)) Then
d1 = Array.ConvertAll(Of String, Decimal)(strArray, Convert.ToDecimal)
End If
End Sub

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.






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

6 comments:

simi said...

hi,

First of all. Thanks very much for your useful post.

I just came across your blog and wanted to drop you a note telling you how impressed I was with the information you have posted here.

Please let me introduce you some info related to this post and I hope that it is useful for .Net community.

There is a good C# resource site, Have alook

http://csharptalk.com

simi

Anonymous said...

Great!!! thanks!!!

kevininstructor said...

The VB.NET version needs a slight alteration as follows using VS2008


Dim SomeArray() As String = {"1164", "2.213", "29"}
Dim decimals() As Decimal
If SomeArray.All(Function(number) Decimal.TryParse(number, Nothing)) Then
decimals = Array.ConvertAll(Of String, Decimal)(SomeArray, Function(c As String) CDec(c))
Console.WriteLine("Success!!!")
End If

Suprotim Agarwal said...

Thanks Kevin for the VB.NET code.

kevininstructor said...

Your welcome and thank you for sharing your expertise!!!

ShaunnyBwoy said...

Thanks for the tip. Very useful bit of code. Is there a way to change type formats? I've needing to change decimal formats from en-GB culture to nl-NL.