หากต้องการรวมอาร์เรย์ที่จัดเรียงไว้สองชุดเข้าในรายการ ให้ตั้งค่าอาร์เรย์ที่จัดเรียงไว้สองชุดก่อน -
int[] array1 = { 1, 2 };
int[] array2 = { 3, 4 }; เพิ่มลงในรายการและรวม -
var list = new List<int>();
for (int i = 0; i < array1.Length; i++) {
list.Add(array1[i]);
list.Add(array2[i]);
} ตอนนี้ ใช้วิธี ToArray() เพื่อแปลงกลับเป็นอาร์เรย์ดังที่แสดงด้านล่าง -
ตัวอย่าง
using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
int[] array1 = { 56, 70, 77};
int[] array2 = { 80, 99, 180};
var list = new List<int>();
for (int i = 0; i < array1.Length; i++) {
list.Add(array1[i]);
list.Add(array2[i]);
}
int[] array3 = list.ToArray();
foreach(int res in array3) {
Console.WriteLine(res);
}
}
} ผลลัพธ์
56 80 70 99 77 180