如何使用索引向 C# 列表中插入项?


首先,设置一个列表 −

List<int> list = new List<int>();
list.Add(456);
list.Add(321);
list.Add(123);
list.Add(877);
list.Add(588);
list.Add(459);

现在,添加一个项目,假设为 index 5;为此,使用 Insert() 方法 −

list.Insert(5, 999);

让我们看看完整的示例 −

示例

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(456);
         list.Add(321);
         list.Add(123);
         list.Add(877);
         list.Add(588);
         list.Add(459);
         Console.Write("List: ");

         foreach (int i in list) {
            Console.Write(i + " ");
         }
         Console.WriteLine("
Count: {0}", list.Count);          // inserting element at index 5          list.Insert(5, 999);          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 日

3K+ 查看数

开启你的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.