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


当前回答

你可以写一个扩展方法:

public static T[] Concat<T>(this T[] x, T[] y)
{
    if (x == null) throw new ArgumentNullException("x");
    if (y == null) throw new ArgumentNullException("y");
    int oldLen = x.Length;
    Array.Resize<T>(ref x, x.Length + y.Length);
    Array.Copy(y, 0, x, oldLen, y.Length);
    return x;
}

然后:

int[] x = {1,2,3}, y = {4,5};
int[] z = x.Concat(y); // {1,2,3,4,5}

其他回答

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

对于小于10000个元素的数组:

using System.Linq;

int firstArray = {5,4,2};
int secondArray = {3,2,1};

int[] result = firstArray.ToList().Concat(secondArray.ToList()).toArray();

我选择了一种更通用的解决方案,它允许连接同一类型的一维数组的任意集。(我一次连接了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}

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

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或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表达式是最慢的。所花费的时间取决于数组元素的类型,但除非有数百万次调用,否则方法之间没有显著差异。