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> Items = new List<int>();  

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

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

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

其他回答

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

试试这个:

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

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

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

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

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

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调用等)。 无论如何,除非你真的需要尝试和优化,否则你目前正走在通往“万恶之源”的道路上;)