矩阵阵列C# [英] matrix to array c#
本文介绍了矩阵阵列C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这将是转换如
1 2 3
4 5 6平方矩阵的最有效方法
7 8 9
到
[1 2 3 4 5 6 7 8 9]
在C#
我是做
INT [,] array2D =新INT [,] {{1,2,3},{4,5,6},{7,8,9}};
INT [] array1D =新INT [9];
INT CI = 0;
的for(int i = 0;我3;;我++)
{
为(INT J = 0; J< 3; J ++)
{
array1D [CI +] = array2D [I,J]);
}
}
解决方案
您'重新总是最好分配完整的结果数组中的一击,然后复制数据
您应该找到这样的总规模;
VAR大小= arrays.Sum(A =>则为a.length);
VAR的结果=新的INT [大小]
和再复制,而不是循环使用自己的Array.CopyTo阵列;
VAR光标= 0;
的foreach(数组中的一个变种){
a.CopyTo(结果,光标);
光标+ =则为a.length;
}
Array.CopyTo会比你自己的循环速度更快;至少不慢。它可能会使用 C'S的memcpy 函数在内部做了一个低级别的块复制。这是有效,因为你可以。
Which would be the most efficient way to convert a squared matrix like
1 2 3
4 5 6
7 8 9
into
[1 2 3 4 5 6 7 8 9]
in c#
I was doing
int[,] array2D = new int[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int[] array1D = new int[9];
int ci=0;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
array1D[ci++] = array2D[i, j]);
}
}
解决方案
You're always better off allocating the complete result array in one hit, then copying the data in.
You should find the total size like this;
var size = arrays.Sum(a=> a.Length);
var result = new int[size];
And then copy the arrays using Array.CopyTo, instead of looping yourself;
var cursor = 0;
foreach(var a in arrays) {
a.CopyTo(result, cursor);
cursor += a.Length;
}
Array.CopyTo will be faster than your own loop; at least, not slower. It will probably use C's memcpy function internally to do a low-level block copy. This is as efficient as you can be.
这篇关于矩阵阵列C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文