有没有办法一次性创建一个包含给定数量元素的 C# 列表?不只是一一相加,或者从其他IEnumerable复制过来。然后我可以使用索引器来分配值。我找到了一个构造函数List(int capacity)。有帮助吗?
嗯,你可以这样说
var List<MyType> result = Enumerable
.Range(0, count)
.Select(index => create your type instance here)
.ToList();
Run Code Online (Sandbox Code Playgroud)
您可能不需要额外的步骤(因为您可以通过 填写列表Select)。如果您正在寻找性能那么
// new List<MyType>(count) reserves memory for "count" items
// so "Add" will not reallocate the list
var List<MyType> result = new List<MyType>(count);
for (int i = 0; i < count; ++i)
result.Add(create your type instance here);
Run Code Online (Sandbox Code Playgroud)