简体   繁体   English

有没有什么方法可以制作一个包含许多元素的C#List?

[英]Any way to make a C# List with a number of elements?

Any way to make a C# List with a given number of elements all at once? 是否可以同时制作具有给定数量元素的C#List? Not just add one by one, or copied from other IEnumerable. 不只是逐个添加,或从其他IEnumerable复制。 Then I can use indexers to assign values. 然后我可以使用索引器来分配值。 I found a constructor List(int capacity) . 我找到了一个构造函数List(int capacity) Does it help? 有帮助吗?

Well, you can put it like this 好吧,你可以这样说

 var List<MyType> result = Enumerable
   .Range(0, count)
   .Select(index => create your type instance here)
   .ToList();

and you may, probably, don't want additional steps (since you can fill the list via Select ). 您可能不希望有其他步骤(因为您可以通过Select填写列表)。 If you're looking for performance then 如果你正在寻找表现那么

 // 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM