ในการลบองค์ประกอบออกจากอาร์เรย์ C# เราจะย้ายองค์ประกอบจากตำแหน่งที่ผู้ใช้ต้องการให้องค์ประกอบลบ
ก่อนอื่นเรามี 5 องค์ประกอบ -
int[] arr = new int[5] {35, 50, 55, 77, 98}; สมมติว่าเราจำเป็นต้องลบองค์ประกอบที่ตำแหน่งที่ 2 เช่น มีการตั้งค่าตัวแปร “pos =2” เพื่อเปลี่ยนองค์ประกอบหลังจากตำแหน่งที่ระบุ –
// Shifting elements
for (i = pos-1; i < 4; i++) {
arr[i] = arr[i + 1];
} ตอนนี้แสดงผลตามที่แสดงในโค้ดด้านล่างทั้งหมด
ตัวอย่าง
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
class Program {
static void Main() {
int i = 0;
int pos;
int[] arr = new int[5] {35, 50, 55, 77, 98};
Console.WriteLine("Elements before deletion:");
for (i = 0; i < 5; i++) {
Console.WriteLine("Element[" + (i) + "]: "+arr[i]);
}
// Let's say the position to delete the item is 2 i.e. arr[1]
pos = 2;
// Shifting elements
for (i = pos-1; i < 4; i++) {
arr[i] = arr[i + 1];
}
Console.WriteLine("Elements after deletion: ");
for (i = 0; i < 4; i++) {
Console.WriteLine("Element[" + (i + 1) + "]: "+arr[i]);
}
Console.WriteLine();
}
}
} ผลลัพธ์
Elements before deletion: Element[0]: 35 Element[1]: 50 Element[2]: 55 Element[3]: 77 Element[4]: 98 Elements after deletion: Element[1]: 35 Element[2]: 55 Element[3]: 77 Element[4]: 98