简体   繁体   English

如何在C#中将十进制数组转换为字符串数组?

[英]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: 是的,您可以非常简单地使用Array.ConvertAll您只需要提供转换委托,而使用lambda表达式最容易做到:

string[] strings = Array.ConvertAll(numbers, x => x.ToString());

Slightly less efficiently, but more idiomatically and flexibly, you can use LINQ: 可以使用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. 这里的灵活性是numbers可以更改为任何 IEnumerable<decimal> -因此,如果更改为使用List<decimal> ,则无需更改此转换代码。

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. 调用ToArray时效率稍有下降,是因为调用Select的结果是一个延迟计算的序列,该序列不知道其大小以开始-因此它无法立即知道输出数组的确切大小,而ConvertAll显然可以。

Of course you can use Array.ConvertAll method. 当然可以使用Array.ConvertAll方法。 You just need a conversation which can be done easyly with lambda expression. 您只需要一个可以通过lambda表达式轻松完成的对话。

string[] string_array = Array.ConvertAll(decimal_array, x => x.ToString());

Array.ConvertAll converts an entire array. Array.ConvertAll转换整个数组。 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 . 这是一个DEMO

Try this 尝试这个

decimal[] decArr = new decimal[5];
// ...
string[] strArr = decArr.Select(d => d.ToString("0.00")).ToArray();

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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