简体   繁体   中英

How to convert decimal array to string array in C#?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM