ประการแรก ตั้งค่าสองอาร์เรย์ -
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 };
// displaying array1
Console.WriteLine("Array 1...");
foreach(int ele in arr1) {
Console.WriteLine(ele);
}
// displaying 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