c# - 在列表中的特定位置添加项目
问题描述
我正在尝试查找是否可以在特定位置的列表中添加项目。例子
string[] tokens= new string[10];
tokens[5]="TestString";
当我试图列出这个
List<string> mitems = new List<string>();
mitems.Insert(5, "TestString");
我在超出范围的列表索引中得到错误列表。有没有与此相关的列表?
解决方案
使用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
推荐阅读
- python - 具有功能的自定义异常
- python - AttributeError:模块“asyncio”没有属性“create_task”
- tensorflow - TFRecord IO 比 python hdf5 阅读器慢,如何提高它的速度?
- php - 无法使用 AJAX 在 codeigniter 中获取延迟加载数据
- swift - Facebook 分享对话框失败 - 操作无法迅速完成
- c++ - 如何避免在 rand() 函数生成的矩阵中使用相同的成员?
- php - 如何在 symfony 中修改内存限制
- docker - Kafka访问docker内外
- amazon-web-services - 是否可以在没有负载均衡器的情况下完全阻止在 aws 中使用 WAF 的某些特定国家/地区?
- firebase - 查询 Firestore 以获取一系列 documentID 中的文档