int[] x = new int [] { 1, 2, 3};
int[] y = new int [] { 4, 5 };

int[] z = // your answer here...

Debug.Assert(z.SequenceEqual(new int[] { 1, 2, 3, 4, 5 }));

现在我用

int[] z = x.Concat(y).ToArray();

有没有更简单或更有效的方法?


使用Concat方法时要小心。c#中的数组拼接这篇文章解释了:

var z = x.Concat(y).ToArray();

对于大型阵列来说效率很低。这意味着Concat方法仅适用于中型数组(最多10000个元素)。


当前回答

int[] scores = { 100, 90, 90, 80, 75, 60 };
int[] alice = { 50, 65, 77, 90, 102 };
int[] scoreBoard = new int[scores.Length + alice.Length];

int j = 0;
for (int i=0;i<(scores.Length+alice.Length);i++)  // to combine two arrays
{
    if(i<scores.Length)
    {
        scoreBoard[i] = scores[i];
    }
    else
    {
        scoreBoard[i] = alice[j];
        j = j + 1;

    }
}


for (int l = 0; l < (scores.Length + alice.Length); l++)
{
    Console.WriteLine(scoreBoard[l]);
}

其他回答

你可以按照你提到的方式来做,或者如果你想要真正的手动操作,你可以滚动你自己的循环:

string[] one = new string[] { "a", "b" };
string[] two = new string[] { "c", "d" };
string[] three;

three = new string[one.Length + two.Length];

int idx = 0;

for (int i = 0; i < one.Length; i++)
    three[idx++] = one[i];
for (int j = 0; j < two.Length; j++)
    three[idx++] = two[j];

我选择了一种更通用的解决方案,它允许连接同一类型的一维数组的任意集。(我一次连接了3个+。)

我的函数:

public static T[] ConcatArrays<T>(params T[][] list)
{
    var result = new T[list.Sum(a => a.Length)];
    int offset = 0;
    for (int x = 0; x < list.Length; x++)
    {
        list[x].CopyTo(result, offset);
        offset += list[x].Length;
    }
    return result;
}

和用法:

int[] a = new int[] { 1, 2, 3 };
int[] b = new int[] { 4, 5, 6 };
int[] c = new int[] { 7, 8 };
var y = ConcatArrays(a, b, c); //Results in int[] {1,2,3,4,5,6,7,8}

使用Buffer更有效(更快)。对数组进行BlockCopy。CopyTo,

int[] x = new int [] { 1, 2, 3};
int[] y = new int [] { 4, 5 };

int[] z = new int[x.Length + y.Length];
var byteIndex = x.Length * sizeof(int);
Buffer.BlockCopy(x, 0, z, 0, byteIndex);
Buffer.BlockCopy(y, 0, z, byteIndex, y.Length * sizeof(int));

我写了一个简单的测试程序来“加热Jitter”,在发布模式下编译,并在没有调试器的情况下在我的机器上运行。

对于问题中例子的10,000,000次迭代

Concat花了3088ms CopyTo耗时1079ms BlockCopy耗时603毫秒

如果我将测试数组改变为从0到99的两个序列,那么我会得到类似于这样的结果,

Concat花了45945ms CopyTo花了2230ms BlockCopy耗时1689ms

从这些结果中,我可以断言CopyTo和BlockCopy方法明显比Concat更有效,此外,如果性能是一个目标,BlockCopy比CopyTo更有价值。

要注意这个答案,如果性能不重要,或者迭代很少,请选择您认为最简单的方法。缓冲区。BlockCopy确实提供了一些超出这个问题范围的类型转换实用程序。

您可以取消ToArray()调用结束。是否有理由在调用Concat之后需要它是一个数组?

调用Concat在两个数组上创建迭代器。它不会创建一个新的数组,所以您没有为一个新数组使用更多的内存。当你调用ToArray时,你实际上创建了一个新数组,并为新数组占用内存。

因此,如果你只是需要轻松迭代,然后调用Concat。

试试下面的方法:

T[] r1 = new T[size1];
T[] r2 = new T[size2];

List<T> targetList = new List<T>(r1);
targetList.Concat(r2);
T[] targetArray = targetList.ToArray();