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.
Tweet
6 comments:
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
Great!!! thanks!!!
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
Thanks Kevin for the VB.NET code.
Your welcome and thank you for sharing your expertise!!!
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.
Post a Comment