ประการแรก ประกาศและเริ่มต้นสองอาร์เรย์ -
int[] arr1 = { 37, 45, 65 };
int[] arr2 = { 70, 89, 118 }; ตอนนี้สร้างรายการใหม่ -
var myList = new List<int>(); myList.AddRange(arr1); myList.AddRange(arr2);
ใช้ AddRange() วิธีการอาร์เรย์ในรายการที่สร้างขึ้นใหม่
myList.AddRange(arr1); myList.AddRange(arr2);
ตอนนี้แปลงรายการเป็นอาร์เรย์ตามที่แสดงด้านล่าง -
ตัวอย่าง
using System;
using System.Collections.Generic;
class Demo {
static void Main() {
int[] arr1 = { 37, 45, 65 };
int[] arr2 = { 70, 89, 118 };
// 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("Combined array elements..");
foreach (int res in arr3) {
Console.WriteLine(res);
}
}
} ผลลัพธ์
Array 1... 37 45 65 Array 2... 70 89 118 Combined array elements.. 37 45 65 70 89 118