忽略任何其他概念或其他问题
有两种简单的方法可以实现这一点,数学,或BlockCopy
从源数组中复制指定数量的字节
从特定位置开始到目标数组的特定偏移量
偏移量。
给定
private static int[,] _matrix = new int[3, 3];
示例 1
public static void Add(List<int> lst)
{
var height = _matrix.GetLength(0);
var width = _matrix.GetLength(1);
if (lst.Count != width * height)
throw new ArgumentException($"The number of elements in lst ({lst.Count}) is not equal to the matrix {width * height}");
for (var y = 0; y < height; y++)
for (var x = 0; x < width; x++)
_matrix[y, x] = lst[x + width * y];
}
以下所有示例都有效,因为为 2d 数组分配的后备内存具有传染性
示例 2
public static void Add2(List<int> lst)
{
var width = _matrix.GetLength(0);
var height = _matrix.GetLength(1);
if (lst.Count != width * height)
throw new ArgumentException($"The number of elements in lst ({lst.Count}) is not equal to the matrix {width * height}");
Buffer.BlockCopy(lst.ToArray(), 0, _matrix, 0, lst.Count * sizeof(int));
}
用法
Add(new List<int>{1,2,3,4,5,6,7,8,9});
使用以下方法,它们没有任何优势(速度或其他)...
奖励方式1,指针
public static unsafe void Add3(List<int> lst)
{
var width = _matrix.GetLength(0);
var height = _matrix.GetLength(1);
if (lst.Count != width * height)
throw new ArgumentException($"The number of elements in lst ({lst.Count}) is not equal to the matrix {width * height}");
fixed (int* p = _matrix)
for (var i = 0; i < lst.Count; i++)
p[i] = lst[i];
}
奖励方式 2,PInvoke memcpy
[DllImport("msvcrt.dll", EntryPoint = "memcpy", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
public static extern IntPtr memcpy(IntPtr dest, IntPtr src, uint count);
public static unsafe void Add4(List<int> lst)
{
var width = _matrix.GetLength(0);
var height = _matrix.GetLength(1);
if (lst.Count != width * height)
throw new ArgumentException($"The number of elements in lst ({lst.Count}) is not equal to the matrix {width * height}");
fixed (int* pDest = _matrix, pSource = lst.ToArray())
memcpy((IntPtr)pDest, (IntPtr)pSource, (uint)(lst.Count * sizeof(int)));
}