如何在 C# 中将项目插入到列表中的给定位置?

csharpprogrammingserver side programming更新于 2025/5/25 5:22:17

要将项目插入到已创建的列表中,请使用 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() 方法 −

// 在第 4 个位置插入元素
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 + " ");
         }
         // 在第 4 个位置插入元素
         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);       }    } }

相关文章