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

其他回答

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

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

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

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

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

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

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

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

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

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

var z = new int[x.Length + y.Length];
x.CopyTo(z, 0);
y.CopyTo(z, x.Length);

我发现了一个优雅的一行解决方案,使用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表达式是最慢的。所花费的时间取决于数组元素的类型,但除非有数百万次调用,否则方法之间没有显著差异。