首先,设置两个数组-
int[] arr1 = { 15, 20, 27, 56 }; int[] arr2 = { 62, 69, 76, 92 };
现在创建一个新列表并使用AddRange()
合并方法-
var myList = new List<int>(); myList.AddRange(arr1); myList.AddRange(arr2);
之后,将合并的集合转换为数组-
int[] arr3 = myList.ToArray()
让我们看完整的代码
using System; using System.Collections.Generic; class Demo { static void Main() { int[] arr1 = { 15, 20, 27, 56 }; int[] arr2 = { 62, 69, 76, 92 }; //显示array1- Console.WriteLine("Array 1..."); foreach(int ele in arr1) { Console.WriteLine(ele); } //显示array2- Console.WriteLine("Array 2..."); foreach(int ele in arr2) { Console.WriteLine(ele); } var myList = new List<int>(); myList.AddRange(arr1); myList.AddRange(arr2); int[] arr3 = myList.ToArray(); Console.WriteLine("Merged array.."); foreach (int res in arr3) { Console.WriteLine(res); } } }
输出结果
Array 1... 15 20 27 56 Array 2... 62 69 76 92 Merged array.. 15 20 27 56 62 69 76 92