[英]Any way to make a C# List with a number of elements?
是否可以同时制作具有给定数量元素的C#List? 不只是逐个添加,或从其他IEnumerable复制。 然后我可以使用索引器来分配值。 我找到了一个构造函数List(int capacity)
。 有帮助吗?
好吧,你可以这样说
var List<MyType> result = Enumerable
.Range(0, count)
.Select(index => create your type instance here)
.ToList();
您可能不希望有其他步骤(因为您可以通过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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.