如何在 C# 中向 ArrayList 中插入一項?


要向已建立的 ArrayList 中插入一項,請使用 Insert() 方法。

首先,設定元素 -

ArrayList arr = new ArrayList();

arr.Add(45);
arr.Add(78);
arr.Add(33);

現在,假設你需要在第 2 個位置插入一項。為此,請使用 Insert() 方法 -

// inserting element at 2nd position
arr.Insert(1, 90);

讓我們看完整的示例 -

示例

 即時演示

using System;
using System.Collections;

namespace Demo {
   public class Program {
      public static void Main(string[] args) {
         ArrayList arr = new ArrayList();

         arr.Add(45);
         arr.Add(78);
         arr.Add(33);
         Console.WriteLine("Count: {0}", arr.Count);
         Console.Write("ArrayList: ");

         foreach(int i in arr) {
            Console.Write(i + " ");
         }

         // inserting element at 2nd position
         arr.Insert(1, 90);
         Console.Write("
ArrayList after inserting a new element: ");          foreach(int i in arr) {             Console.Write(i + " ");          }          Console.WriteLine("
Count: {0}", arr.Count);       }    } }

輸出

Count: 3
ArrayList: 45 78 33
ArrayList after inserting a new element: 45 90 78 33
Count: 4

更新於: 2020 年 6 月 22 日

429 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告