c# - .Net List<T> 插入

标签 c# .net list

我正在努力

var test = new List< int>(10);

test.Insert(1, 0);
or
test[1] =0;

我在这方面遇到了异常(exception)。

如何插入列表?

谢谢 有足够的空间让这个编辑器正确显示内容。

最佳答案

var test = new List<int>(10);
test.Add(1);

var test = new List<int>(10);
test.Insert(0, 1) // inserts the value in the first position

更新

我错过了你的初衷。要做你想做的,你只需要用一个初始值初始化列表中的每个位置。不那么建议的方式是这样的:

//var test = new List<int>(10){0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
var test = new List<int>(10);
test.AddRange(Enumerable.Repeat(0, 10)); // Thanks to Ahmad
test[3] = 10; // works now

关于c# - .Net List<T> 插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1488193/

相关文章:

c# - 在 ASP.NET 页面上显示的 SQL <二进制数据> 图像类型

JavaScript 使用程序集名称直接调用 C# web 服务方法

c# - 难以将图像保存到 MemoryStream

c# - 无法绑定(bind)多部分标识符 "xxx"

c# - 排除以特定字符开头的正则表达式匹配

javascript - 任何人都知道在ReactJS中编写此代码的简便方法

list - 检查2个列表是否有相等的元素 Haskell

python - 比较大列表中的项目 - 查找长度相差 1 个字母的项目 - Python

c# - 获取 Azure 文件共享 (CloudFileDirectory) 中的所有文件

c# - GridView 对行进行分组并更改颜色