如何在 C# 中连接两个数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1547252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I concatenate two arrays in C#?
提问by hwiechers
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 }));
Right now I use
现在我用
int[] z = x.Concat(y).ToArray();
Is there an easier or more efficient method?
有没有更简单或更有效的方法?
采纳答案by Zed
var z = new int[x.Length + y.Length];
x.CopyTo(z, 0);
y.CopyTo(z, x.Length);
回答by Mike Two
You can take the ToArray() call off the end. Is there a reason you need it to be an array after the call to Concat?
您可以在最后取消 ToArray() 调用。在调用 Concat 之后,您是否需要将它作为数组?
Calling Concat creates an iterator over both arrays. It does not create a new array so you have not used more memory for a new array. When you call ToArray you actually do create a new array and take up the memory for the new array.
调用 Concat 会在两个数组上创建一个迭代器。它不会创建新数组,因此您没有为新数组使用更多内存。当您调用 ToArray 时,您实际上确实创建了一个新数组并占用了新数组的内存。
So if you just need to easily iterate over both then just call Concat.
因此,如果您只需要轻松地遍历两者,那么只需调用 Concat。
回答by Adriaan Stander
Try this:
尝试这个:
List<int> list = new List<int>();
list.AddRange(x);
list.AddRange(y);
int[] z = list.ToArray();
回答by mezoid
For int[] what you've done looks good to me. astander'sanswer would also work well for List<int>
.
对于 int[] 你所做的对我来说看起来不错。旁观者的回答也适用于List<int>
.
回答by dreadwail
You can do it the way you have referred to, or if you want to get really manual about it you can roll your own loop:
你可以按照你提到的方式来做,或者如果你想获得真正的手册,你可以滚动你自己的循环:
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];
回答by Marc Gravell
You could write an extension method:
你可以写一个扩展方法:
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;
}
Then:
然后:
int[] x = {1,2,3}, y = {4,5};
int[] z = x.Concat(y); // {1,2,3,4,5}
回答by TToni
The most efficient structure in terms of RAM (and CPU) to hold the combined array would be a special class that implements IEnumerable (or if you wish even derives from Array) and links internally to the original arrays to read the values. AFAIK Concat does just that.
就 RAM(和 CPU)而言,保存组合数组的最有效结构是一个特殊的类,它实现 IEnumerable(或者,如果您希望甚至从 Array 派生)并在内部链接到原始数组以读取值。AFAIK Concat 就是这样做的。
In your sample code you could omit the .ToArray() though, which would make it more efficient.
在您的示例代码中,您可以省略 .ToArray() ,这会使其更有效率。
回答by Siewers
What you need to remember is that when using LINQ you are utilizing delayed execution. The other methods described here all work perfectly, but they are executed immediately. Furthermore the Concat() function is probably optimized in ways you can't do yourself (calls to internal API's, OS calls etc.). Anyway, unless you really need to try and optimize, you're currently on your path to "the root of all evil" ;)
您需要记住的是,在使用 LINQ 时,您正在使用延迟执行。此处描述的其他方法都可以完美运行,但它们会立即执行。此外,Concat() 函数可能以您自己无法完成的方式进行了优化(调用内部 API、操作系统调用等)。无论如何,除非您真的需要尝试和优化,否则您目前正走在通往“万恶之源”的道路上;)
回答by deepee1
I settled on a more general-purpose solution that allows concatenating an arbitrary set of one-dimensional arrays of the same type. (I was concatenating 3+ at a time.)
我选择了一个更通用的解决方案,它允许连接任意一组相同类型的一维数组。(我一次连接 3+。)
My function:
我的功能:
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;
}
And usage:
和用法:
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}
回答by Sergey Shteyn
public static T[] Concat<T>(this T[] first, params T[][] arrays)
{
int length = first.Length;
foreach (T[] array in arrays)
{
length += array.Length;
}
T[] result = new T[length];
length = first.Length;
Array.Copy(first, 0, result, 0, first.Length);
foreach (T[] array in arrays)
{
Array.Copy(array, 0, result, length, array.Length);
length += array.Length;
}
return result;
}