[英]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.