如何解决将列表中的元素添加到C#中的2D数组
我有一个名为Matrix的类,因此基本上我创建了一个名为addElemts的方法,该方法将整数值列表作为参数。 现在,我想获取列表中的值并将它们放入矩阵中,但是我使用的逻辑似乎是获取列表中的最后一个元素,这不是期望的结果。
public void addElemts(List<int> lst)
{
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
{
foreach (int itm in lst)
{
a[i,j] = itm;
}
}
}
解决方法
忽略概念上或其他方面的任何其他问题
有两种简单的方法可以实现这一目标: Math 或BlockCopy
从源数组中复制指定数量的字节,起始于a 从特定位置开始到目标数组的特定偏移量 偏移量。
给予
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(),_matrix,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,调用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)));
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。