C# 在 .NET 中合并两个数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/59217/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 10:17:24  来源:igfitidea点击:

Merging two arrays in .NET

提问by kbrinley

Is there a built in function in .NET 2.0 that will take two arrays and merge them into one array?

.NET 2.0 中是否有一个内置函数可以将两个数组合并为一个数组?

The arrays are both of the same type. I'm getting these arrays from a widely used function within my code base and can't modify the function to return the data in a different format.

数组都是相同的类型。我从代码库中广泛使用的函数中获取这些数组,但无法修改该函数以返回不同格式的数据。

I'm looking to avoid writing my own function to accomplish this if possible.

如果可能,我希望避免编写自己的函数来完成此操作。

采纳答案by Blair Conrad

If you can manipulate one of the arrays, you can resize it before performing the copy:

如果您可以操作其中一个数组,则可以在执行复制之前调整其大小:

T[] array1 = getOneArray();
T[] array2 = getAnotherArray();
int array1OriginalLength = array1.Length;
Array.Resize<T>(ref array1, array1OriginalLength + array2.Length);
Array.Copy(array2, 0, array1, array1OriginalLength, array2.Length);

Otherwise, you can make a new array

否则,您可以创建一个新数组

T[] array1 = getOneArray();
T[] array2 = getAnotherArray();
T[] newArray = new T[array1.Length + array2.Length];
Array.Copy(array1, newArray, array1.Length);
Array.Copy(array2, 0, newArray, array1.Length, array2.Length);

More on available Array methods on MSDN.

有关 MSDN 上可用 Array 方法的更多信息

回答by GEOCHET

I think you can use Array.Copyfor this. It takes a source index and destination index so you should be able to append the one array to the other. If you need to go more complex than just appending one to the other, this may not be the right tool for you.

我认为您可以为此使用Array.Copy。它需要一个源索引和目标索引,因此您应该能够将一个数组附加到另​​一个数组。如果您需要做的不仅仅是将一个附加到另一个更复杂,那么这可能不是适合您的工具。

回答by Joel Coehoorn

Assuming the destination array has enough space, Array.Copy()will work. You might also try using a List<T>and its .AddRange()method.

假设目标数组有足够的空间,Array.Copy()将起作用。您也可以尝试使用 aList<T>及其.AddRange()方法。

回答by apandit

I'm assuming you're using your own array types as opposed to the built-in .NET arrays:

我假设您使用的是自己的数组类型,而不是内置的 .NET 数组:

public string[] merge(input1, input2)
{
    string[] output = new string[input1.length + input2.length];
    for(int i = 0; i < output.length; i++)
    {
        if (i >= input1.length)
            output[i] = input2[i-input1.length];
        else
            output[i] = input1[i];
    }
    return output;
}

Another way of doing this would be using the built in ArrayList class.

另一种方法是使用内置的 ArrayList 类。

public ArrayList merge(input1, input2)
{
    Arraylist output = new ArrayList();
    foreach(string val in input1)
        output.add(val);
    foreach(string val in input2)
        output.add(val);
    return output;
}

Both examples are C#.

两个示例都是 C#。

回答by Blair Conrad

First, make sure you ask yourself the question "Should I really be using an Array here"?

首先,确保你问自己这个问题“我真的应该在这里使用数组吗”?

Unless you're building something where speed is of the utmost importance, a typed List, like List<int>is probably the way to go. The only time I ever use arrays are for byte arrays when sending stuff over the network. Other than that, I never touch them.

除非您正在构建速度至关重要的东西,否则类型列表,likeList<int>可能是要走的路。我唯一一次使用数组是在通过网络发送内容时使用字节数组。除此之外,我从不碰它们。

回答by OwenP

In C# 3.0 you can use LINQ's Concatmethod to accomplish this easily:

在 C# 3.0 中,您可以使用 LINQ 的Concat方法轻松完成此操作:

int[] front = { 1, 2, 3, 4 };
int[] back = { 5, 6, 7, 8 };
int[] combined = front.Concat(back).ToArray();

In C# 2.0 you don't have such a direct way, but Array.Copy is probably the best solution:

在 C# 2.0 中你没有这样直接的方式,但 Array.Copy 可能是最好的解决方案:

int[] front = { 1, 2, 3, 4 };
int[] back = { 5, 6, 7, 8 };

int[] combined = new int[front.Length + back.Length];
Array.Copy(front, combined, front.Length);
Array.Copy(back, 0, combined, front.Length, back.Length);

This could easily be used to implement your own version of Concat.

这可以很容易地用于实现您自己的Concat.

回答by namco

Try this:

尝试这个:

ArrayLIst al = new ArrayList();
al.AddRange(array_1);
al.AddRange(array_2);
al.AddRange(array_3);
array_4 = al.ToArray();

回答by pasx

Here is a simple example using Array.CopyTo. I think that it answers your question and gives an example of CopyTo usage - I am always puzzled when I need to use this function because the help is a bit unclear - the index is the position in the destination array where inserting occurs.

这是一个使用 Array.CopyTo 的简单示例。我认为它回答了您的问题并给出了 CopyTo 用法的示例 - 当我需要使用此函数时我总是感到困惑,因为帮助有点不清楚 - 索引是目标数组中发生插入的位置。

int[] xSrc1 = new int[3] { 0, 1, 2 };
int[] xSrc2 = new int[5] { 3, 4, 5, 6 , 7 };

int[] xAll = new int[xSrc1.Length + xSrc2.Length];
xSrc1.CopyTo(xAll, 0);
xSrc2.CopyTo(xAll, xSrc1.Length);

I guess you can't get it much simpler.

我想你不能让它变得更简单。

回答by vikasse

int [] SouceArray1 = new int[] {2,1,3};
int [] SourceArray2 = new int[] {4,5,6};
int [] targetArray = new int [SouceArray1.Length + SourceArray2.Length];
SouceArray1.CopyTo(targetArray,0);
SourceArray2.CopyTo(targetArray,SouceArray1.Length) ; 
foreach (int i in targetArray) Console.WriteLine(i + " ");  

Using the above code two Arrays can be easily merged.

使用上面的代码可以很容易地合并两个数组。

回答by Lorenz Lo Sauer

Personally, I prefer my own Language Extensions, which I add or remove at will for rapid prototyping.

就个人而言,我更喜欢我自己的语言扩展,我可以随意添加或删除它以进行快速原型设计。

Following is an example for strings.

以下是字符串的示例。

//resides in IEnumerableStringExtensions.cs
public static class IEnumerableStringExtensions
{
   public static IEnumerable<string> Append(this string[] arrayInitial, string[] arrayToAppend)
   {
       string[] ret = new string[arrayInitial.Length + arrayToAppend.Length];
       arrayInitial.CopyTo(ret, 0);
       arrayToAppend.CopyTo(ret, arrayInitial.Length);

       return ret;
   }
}

It is much faster than LINQ and Concat. Faster still, is using a custom IEnumerableType-wrapper which stores references/pointers of passed arrays and allows looping over the entire collection as if it were a normal array. (Useful in HPC, Graphics Processing, Graphics render...)

它比 LINQ 和 Concat 快得多。更快的是,使用自定义IEnumerable类型包装器存储传递数组的引用/指针,并允许循环遍历整个集合,就好像它是一个普通数组一样。(在 HPC、图形处理、图形渲染中很有用...)

Your Code:

您的代码:

var someStringArray = new[]{"a", "b", "c"};
var someStringArray2 = new[]{"d", "e", "f"};
someStringArray.Append(someStringArray2 ); //contains a,b,c,d,e,f

For the entire code and a generics version see: https://gist.github.com/lsauer/7919764

有关完整代码和泛型版本,请参见:https: //gist.github.com/lsauer/7919764

Note:This returns an unextended IEnumerable object. To return an extended object is a bit slower.

注意:这将返回一个未扩展的 IEnumerable 对象。返回扩展对象有点慢。

I compiled such extensions since 2002, with a lot of credits going to helpful people on CodeProject and 'Stackoverflow'. I will release these shortly and put the link up here.

我从 2002 年开始编译这样的扩展,很多功劳都给了 CodeProject 和“Stackoverflow”上有帮助的人。我将很快发布这些并将链接放在这里。