首先,设置一个列表-
List<int> list = new List<int>(); list.Add(456); list.Add(321); list.Add(123); list.Add(877); list.Add(588); list.Add(459);
现在,要在索引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("\nCount: {0}", list.Count); //在索引5处插入元素 list.Insert(5, 999); Console.Write("\nList after inserting a new element: "); foreach (int i in list) { Console.Write(i + " "); } Console.WriteLine("\nCount: {0}", list.Count); } } }