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个元素)。


当前回答

使用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确实提供了一些超出这个问题范围的类型转换实用程序。

其他回答

public static T[] Concat<T>(this T[] first, params T[][] arrays)
{
    int length = first.Length;
    foreach (T[] array in arrays)
    {
        length += array.Length;
    }
    T[] result = new T[length];
    length = first.Length;
    Array.Copy(first, 0, result, 0, first.Length);
    foreach (T[] array in arrays)
    {
        Array.Copy(array, 0, result, length, array.Length);
        length += array.Length;
    }
    return result;
}

迟回答:-)。

public static class ArrayExtention
    {

        public static T[] Concatenate<T>(this T[] array1, T[] array2)
        {
            T[] result = new T[array1.Length + array2.Length];
            array1.CopyTo(result, 0);
            array2.CopyTo(result, array1.Length);
            return result;
        }

    }

试试下面的方法:

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

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

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

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];

你需要记住的是,当你使用LINQ时,你是在利用延迟执行。这里描述的其他方法都工作得很好,但它们会立即执行。此外,Concat()函数可能以您自己无法实现的方式进行优化(调用内部API, OS调用等)。 无论如何,除非你真的需要尝试和优化,否则你目前正走在通往“万恶之源”的道路上;)