首页 > 解决方案 > 在列表中的特定位置添加项目

问题描述

我正在尝试查找是否可以在特定位置的列表中添加项目。例子

string[] tokens= new string[10];
tokens[5]="TestString";

当我试图列出这个

 List<string> mitems = new List<string>();
 mitems.Insert(5, "TestString");

我在超出范围的列表索引中得到错误列表。有没有与此相关的列表?

标签: c#

解决方案


使用Insert(index, item);方法。

查看MSDN Insert了解更多信息。

但是当您尝试在不存在的索引处插入项目时会出现错误。

您可以使用 10 个空值初始化您的列表,就像您对数组所做的那样,但是如果您使用Insert一个新条目,而不是像字典那样替换旧条目。这意味着您在第一次使用后将有 11 个条目Insert

此示例代码

var items = new List<string>();
items.AddRange(Enumerable.Repeat(string.Empty, 10));
Console.WriteLine(items.Count);
items.Insert(5, "TestString");
Console.WriteLine(items.Count);

给出这个输出(为了更好地理解):

10

11


推荐阅读