在 C# .NET 中使用单个值初始化整数数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14210369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Initialize an integer array with a single value in C# .NET
提问by Farhan Hafeez
Possible Duplicate:
How do I quicky fill an array with a specific value?
可能的重复:
如何使用特定值快速填充数组?
Is there a way to initialize an integer array with a single value like -1 without having to explicitly assign each item?
有没有办法用一个像 -1 这样的值来初始化一个整数数组,而不必显式分配每个项目?
Basically, if I have
基本上,如果我有
int[] MyIntArray = new int[SomeCount];
All items are assigned 0 by default. Is there a way to change that value to -1 without using a loop? or assigning explicitly each item using {}?
默认情况下,所有项目都分配为 0。有没有办法在不使用循环的情况下将该值更改为 -1?或使用 {} 显式分配每个项目?
采纳答案by scartag
int[] myIntArray = Enumerable.Repeat(-1, 20).ToArray();
回答by mlorbetske
If you've got a single value (or just a few) you can set them explicitly using a collection initializer
如果您有一个值(或只有几个),您可以使用集合初始值设定项显式设置它们
int[] MyIntArray = new int[] { -1 };
If you've got lots, you can use Enumerable.Repeatlike this
如果你有很多,你可以使用Enumerable.Repeat这样
int[] MyIntArray = Enumerable.Repeat(-1, YourArraySize).ToArray();
回答by SWeko
You could use the Enumerable.Repeatmethod
您可以使用Enumerable.Repeat方法
int[] myIntArray = Enumerable.Repeat(1234, 1000).ToArray()
will create an array of 1000 elements, that all have the value of 1234.
将创建一个包含 1000 个元素的数组,所有元素的值都是 1234。