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

其他回答

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

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

就RAM(和CPU)而言,保存组合数组的最有效结构是一个特殊的类,它实现IEnumerable(或者如果您希望从array派生),并在内部链接到原始数组以读取值。AFAIK Concat就是这么做的。

在示例代码中,您可以省略. toarray(),这将使它更有效。

迟回答:-)。

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

    }

我发现了一个优雅的一行解决方案,使用LINQ或Lambda表达式,两者工作相同(当程序编译时LINQ转换为Lambda)。该解决方案适用于任何数组类型和任何数量的数组。

使用LINQ:

public static T[] ConcatArraysLinq<T>(params T[][] arrays)
{
    return (from array in arrays
            from arr in array
            select arr).ToArray();
}

使用λ:

public static T[] ConcatArraysLambda<T>(params T[][] arrays)
{
    return arrays.SelectMany(array => array.Select(arr => arr)).ToArray();
}

这两种我都提供了。性能方面@Sergey Shteyn的或@deepee1的解决方案更快一些,Lambda表达式是最慢的。所花费的时间取决于数组元素的类型,但除非有数百万次调用,否则方法之间没有显著差异。