i need to convert Decimal array to string array . How to convert decimal[] to string[] ? Can i use
Array.ConvertAll()
method to do this task?
i need to convert Decimal array to string array . How to convert decimal[] to string[] ? Can i use
Array.ConvertAll()
method to do this task?
Yes, you can use Array.ConvertAll
pretty simply - you just need to provide the conversion delegate, which is most easily done with a lambda expression:
string[] strings = Array.ConvertAll(numbers, x => x.ToString());
Slightly less efficiently, but more idiomatically and flexibly, you can use LINQ:
string[] strings = numbers.Select(x => x.ToString()).ToArray();
Or if you don't actually need an array, and are happy for it to perform the string conversion every time you iterate over it:
IEnumerable<string> strings = numbers.Select(x => x.ToString());
The flexibility here is that numbers
can change to be any IEnumerable<decimal>
- so if you change to using a List<decimal>
, you won't need to change this conversion code, for example.
The slight loss in efficiency when calling ToArray
is that the result of calling Select
is a lazily-evaluated sequence which doesn't know its size to start with - so it can't know the exact size of output array immediately, whereas ConvertAll
obviously does.
Of course you can use Array.ConvertAll
method. You just need a conversation which can be done easyly with lambda expression.
string[] string_array = Array.ConvertAll(decimal_array, x => x.ToString());
Array.ConvertAll
converts an entire array. It converts all elements in one array to another type.
Let's code it;
decimal[] decimal_array = new decimal[] {1.1M, 1.2M, 1.3M, 1.4M };
string[] string_array = Array.ConvertAll(decimal_array, x => x.ToString());
foreach (var item in string_array)
{
Console.WriteLine("{0} - {1}", item.GetType(), item);
}
Output will be;
System.String - 1.1
System.String - 1.2
System.String - 1.3
System.String - 1.4
Here is a DEMO
.
Try this
decimal[] decArr = new decimal[5];
// ...
string[] strArr = decArr.Select(d => d.ToString("0.00")).ToArray();
Hope this helps
You got me playing with code. lol
Since we are talking about Decimal, which is typically used to represent money, each of your .ToString()
extensions can be overloaded with the Currency formatter .ToString("C")
:
decimal[] decimal_array = new decimal[] { 1.1M, 1.2M, 1.3M, 1.4M };
var consoleText = "";
foreach (var item in decimal_array)
{
consoleText += $"{item.GetType()} - {item.ToString("C")}\n";
}
var array = new decimal[]
{
1.0010M,
1.0480M,
1.0485M,
1.0490M,
1.0495M,
1.0500M,
1.0505M,
1.0510M,
1.0515M,
1.0520M,
};
var moneyView = "";
foreach (var item in Array.ConvertAll(array, x => x.ToString("C")))
{
moneyView += $"{item}, ";
}
Here is a screenshot showing the results: