[英]Convert decimal[][] to double[][] in C#
I want to cast my 2D decimal arrays to double arrays. 我想将2D十进制数组转换为双数组。 I would like this to be done rather efficiently but also be tidy.
我希望这项工作相当有效,但也要整洁。 This looks nice and tidy.
这看起来很整洁。 How can I extend it for 2D arrays?
如何将其扩展为2D阵列?
Am I going to have to loop through the first dimension and apply the Linq/delegate style command or is there another way to do it with less code? 我是否必须遍历第一个维度并应用Linq / delegate样式命令,还是有另一种方法可以用更少的代码来完成它?
PS: I am not very concerned with losing precision past 3-4 decimal places. PS:我不太关心精确度超过3-4位小数。
Update: At the request of a comment, this is what I am proposing although want to avoid: 更新:根据评论的要求,这是我提出的建议虽然想避免:
double[][] inputs = new double[inputsArray.Length][];
for (int i = 0; i < inputsArray.Length; i++)
{
inputs[i] = Array.ConvertAll(inputsArray[i], x => (double)x);
}
Unfortunately with a jagged array you'll have to convert each array separately, but it can still be done in a one-liner: 不幸的是,对于锯齿状阵列,你必须单独转换每个数组,但它仍然可以在一个单行中完成:
doubleArray = Array.ConvertAll(decimalArray, da => Array.ConvertAll(da, d => (double)d));
or using Linq: 或使用Linq:
doubleArray = decimalArray.Select(da => da.Select(d => (double)d).ToArray()).ToArray();
You'll have to try it to see which is faster; 你必须尝试看看哪个更快;
Array.ConvertAll
may have some optimizations by combining the delegate and the Array creation. Array.ConvertAll
可以通过组合委托和数组创建进行一些优化。
BENCHMARKS 基准
to address the debate of performance, I benchmarked the three proposed solutions: 为了解决性能问题,我对提出的三个解决方案进行了基准测试:
Array.Convert
Here are the code and the results 这是代码和结果
int I = 10000;
int J = 1000;
Random rand = new Random();
decimal[][] decimalArray = new decimal[I][];
decimalArray = Enumerable.Range(1,I).Select(i =>
Enumerable.Range(1, J).Select (j => (decimal)rand.NextDouble()).ToArray()
).ToArray();
Stopwatch s = new Stopwatch();
// Array.ConvertAll
s.Start();
var doubleArray = Array.ConvertAll(decimalArray, da => Array.ConvertAll(da, d => (double)d));
s.Stop();
s.Dump();
// Linq
s.Restart();
doubleArray = decimalArray.Select(da => da.Select(d => (double)d).ToArray()).ToArray();
s.Stop();
s.Dump();
// Loops
s.Restart();
doubleArray = new double[I][];
for(int i = 0; i < I; i++)
{
decimal[] dda = decimalArray[i];
doubleArray[i] = new double[dda.Length];
double[] da = doubleArray[i];
for(int j = 0; j < dda.Length; j++)
{
da[j] = (double)dda[j];
}
}
s.Stop();
s.Dump();
Method ElapsedMilliseconds
------------- ----------------------
Array.Convert 310
Linq 478
Loops 287 (7.5% faster that Array.Convert)
You can decide whether a 7.5% speed improvement is worth 7X the amount of code. 您可以决定7.5%的速度提升是否相当于代码量的7倍。
You can concatenate two Array.ConvertAll
eg : 你可以连接两个
Array.ConvertAll
例如:
var dec2D = new decimal[100][];
var dbl2D = Array.ConvertAll(dec2D, x => Array.ConvertAll(x, y => (double)y));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.