什么';在C#中,用较小的数组复制/填充较大数组的最佳方法是什么?

什么';在C#中,用较小的数组复制/填充较大数组的最佳方法是什么?,c#,arrays,.net-2.0,C#,Arrays,.net 2.0,我有一个大的int[]数组和一个小得多的int[]数组。我想用小数组中的值填充大数组,方法是重复将小数组复制到大数组中,直到它满为止(这样大[0]=大[13]=大[26]…=小[0]等等)。我已经有了一个简单的方法: int iSource = 0; for (int i = 0; i < destArray.Length; i++) { if (iSource >= sourceArray.Length) { iSource = 0; // rese

我有一个大的int[]数组和一个小得多的int[]数组。我想用小数组中的值填充大数组,方法是重复将小数组复制到大数组中,直到它满为止(这样大[0]=大[13]=大[26]…=小[0]等等)。我已经有了一个简单的方法:

int iSource = 0;
for (int i = 0; i < destArray.Length; i++)
{
    if (iSource >= sourceArray.Length)
    {
        iSource = 0; // reset if at end of source
    }
    destArray[i] = sourceArray[iSource++];
}
int-isosource=0;
for(int i=0;i=sourceArray.Length)
{
iSource=0;//如果在源的末尾重置
}
destArray[i]=sourceArray[isosource++];
}

但是我需要一些更优雅的东西,希望更快。

使用
Array.Copy()
重载让循环工作,该重载允许您从一个数组复制到目标数组中的特定索引

if (sourceArray.Length == 0) return; // don't get caught in infinite loop

int idx = 0;

while ((idx + sourceArray.Length) < destArray.Length) {
    Array.Copy( sourceArray, 0, destArray, idx, sourceArray.Length);

    idx += sourceArray.Length;
}

Array.Copy( sourceArray, 0, destArray, idx, destArray.Length - idx);
if(sourceArray.Length==0)返回;//不要陷入无限循环
int-idx=0;
而((idx+sourceArray.Length)
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
名称空间临时
{
班级计划
{
静态void Main(字符串[]参数)
{
int[]数组={1,2,3,4,5,6,7,8,9,10,11};
int[]array2=新int[213];
for(int i=0;i=array2.Length)
长度=阵列2.长度-i;
数组.Copy(数组,0,数组2,i,长度);
}
整数计数=0;
foreach(阵列中的int i)
{
Console.Write(i.ToString()++(count++).ToString()++“\n”);
}
Console.Read();
}
}
}
:)

编辑
发现了一个bug,如果它们不能被彼此分割,它就会崩溃。现在修复:)

有趣的是,获胜的答案是提供源阵列时速度最慢的

我要提出的解决办法是

for (int i = 0; i < destArray.Length; i++)
{
    destArray[i] = sourceArray[i%sourceArray.Length];
}
for(int i=0;i
但是,当我使用回答问题中的输入测试超过100000次迭代的性能时,它的性能比提问者循环要差

这是我的小测试应用程序的输出

array copy 164ms (Nelson LaQuet's code) assign copy 77ms (MusiGenesis code) assign mod copy 161ms (headsling's code) 阵列拷贝164ms(Nelson LaQuet代码) 分配副本77ms(MusiGenesis代码) 分配模块副本161ms(车头箱代码)
除非我遗漏了什么,
I%array.Length
永远不会是0以外的任何值。你是说我的原始代码是最快的吗?(我从未对其中任何一项进行过基准测试)是的!分配副本(您的)在100万次迭代中得分为77毫秒。不错吧? array copy 164ms (Nelson LaQuet's code) assign copy 77ms (MusiGenesis code) assign mod copy 161ms (headsling's code)