如何從 C# 陣列中刪除/移除一個元素?
要從 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP