如何在 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.