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[] z = new List<string>()
.Concat(a)
.Concat(b)
.Concat(c)
.ToArray();
此方法可用于初始化级别,例如定义静态数组的静态连接:
public static int[] a = new int [] { 1, 2, 3, 4, 5 };
public static int[] b = new int [] { 6, 7, 8 };
public static int[] c = new int [] { 9, 10 };
public static int[] z = new List<string>()
.Concat(a)
.Concat(b)
.Concat(c)
.ToArray();
但是,你需要注意两点:
Concat方法在两个数组上创建迭代器:它不创建新数组,因此在内存使用方面很有效:然而,随后的ToArray将抵消这种优势,因为它实际上创建了一个新数组,并为新数组占用内存。
正如@Jodrell所说,Concat对于大型数组来说效率相当低:它应该只用于中型数组。
如果必须以性能为目标,可以使用以下方法:
/// <summary>
/// Concatenates two or more arrays into a single one.
/// </summary>
public static T[] Concat<T>(params T[][] arrays)
{
// return (from array in arrays from arr in array select arr).ToArray();
var result = new T[arrays.Sum(a => a.Length)];
int offset = 0;
for (int x = 0; x < arrays.Length; x++)
{
arrays[x].CopyTo(result, offset);
offset += arrays[x].Length;
}
return result;
}
或者(对于喜欢说俏皮话的人):
int[] z = (from arrays in new[] { a, b, c } from arr in arrays select arr).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}