Để xóa một phần tử khỏi mảng C #, chúng tôi sẽ di chuyển các phần tử khỏi vị trí mà người dùng muốn phần tử đó xóa.
Ở đây, đầu tiên chúng ta có 5 yếu tố -
int[] arr = new int[5] {35, 50, 55, 77, 98}; Bây giờ, giả sử chúng ta cần xóa phần tử ở vị trí thứ 2, tức là biến “pos =2” được đặt, để thay đổi các phần tử sau vị trí đã chỉ định -
// Shifting elements
for (i = pos-1; i < 4; i++) {
arr[i] = arr[i + 1];
} Bây giờ, hãy hiển thị kết quả như được hiển thị trong đoạn mã hoàn chỉnh bên dưới.
Ví dụ
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();
}
}
} Đầu ra
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