如何在 C# 中某個給定位置插入一個項到列表?


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

首先,設定元素 -

List <int> list = new List<int>();
list.Add(989);
list.Add(345);
list.Add(654);
list.Add(876);
list.Add(234);
list.Add(909);

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

// inserting element at 4th position
list.Insert(3, 567);

我們來看完整示例 -

示例

using System;
using System.Collections.Generic;

namespace Demo {
   public class Program {
      public static void Main(string[] args) {
         List < int > list = new List < int > ();

         list.Add(989);
         list.Add(345);
         list.Add(654);
         list.Add(876);
         list.Add(234);
         list.Add(909);

         Console.WriteLine("Count: {0}", list.Count);

         Console.Write("List: ");
         foreach(int i in list) {
            Console.Write(i + " ");
         }
         // inserting element at 4th position
         list.Insert(3, 567);
         Console.Write("
List after inserting a new element: ");          foreach(int i in list) {             Console.Write(i + " ");          }          Console.WriteLine("
Count: {0}", list.Count);       }    } }

更新於: 2020 年 6 月 22 日

2K+ 瀏覽

開啟您的職業生涯

透過完成課程並獲得認證

開始學習
廣告
© . All rights reserved.