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


当前回答

试试这个:

List<int> list = new List<int>();
list.AddRange(x);
list.AddRange(y);
int[] z = list.ToArray();

其他回答

我认为列出一份清单很适合这个目的。

你可以创建一个这样的列表。

List<int> Items = new List<int>();  

然后你可以很容易地使用for每个循环遍历任意数量的数组并将它们添加到列表中。

foreach (nameOfArray中的int i) { Items.Add(我); }

如果使用列表,则可以消除出界异常的问题。列表可以用于与数组相同的所有功能。唯一有意义的区别是缺少项目数量的硬性限制。

试试下面的方法:

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

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

你可以写一个扩展方法:

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}

我选择了一种更通用的解决方案,它允许连接同一类型的一维数组的任意集。(我一次连接了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}
static class Extensions
{
    public static T[] Concat<T>(this T[] array1, params T[] array2) => ConcatArray(array1, array2);

    public static T[] ConcatArray<T>(params T[][] arrays)
    {
        int l, i;

        for (l = i = 0; i < arrays.Length; l += arrays[i].Length, i++);

        var a = new T[l];

        for (l = i = 0; i < arrays.Length; l += arrays[i].Length, i++)
            arrays[i].CopyTo(a, l);

        return a;
    }
}

我认为上面的解决方案比我在这里看到的其他解决方案更普遍和更轻。它更通用,因为它不限制只对两个数组进行连接,也更轻便,因为它不使用LINQ和List。

注意,这个解决方案很简洁,并且添加的通用性不会增加大量的运行时开销。