通过循环创建数组
我需要创建一个字符串数组,很简单...唯一的问题是字符串是 1-1000 之间的整数,我真的不想键入每个字符串。
你能创建一个可以创建这个的循环吗?
现在它看起来像这样
private readonly string[] _myArray = { "1", "2", "3", "4", "5" };
,并且有
for (var i = 0; i < _myArray.Length; i++)
{
arFoo[i].SetBar(_myArray[i]);
}
任何有关如何添加其他 995 而无需手动输入的建议来调用它吗?
I need to create an array of strings, easy enough... the only problem is that the strings are integers from 1-1000 and I really dont want to type each of them.
Can you create a loop that could create this?
right now it looks like this
private readonly string[] _myArray = { "1", "2", "3", "4", "5" };
and its called by
for (var i = 0; i < _myArray.Length; i++)
{
arFoo[i].SetBar(_myArray[i]);
}
any suggestions on how to add the other 995 without manually typing them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
这很简单又干净:
This is simple and clean:
如果您想使用 LINQ:
或更传统的方式:
If you want to use LINQ:
Or more traditionally:
怎么样
How about
你需要一个数组吗?您可以这样做:
如果您确实需要数组,请了解 C#(和 .Net)中的数组是固定大小的。您需要另一个数据结构,例如
List
来添加元素,然后您可以通过ToArray()
转换为数组(如果确实需要)。Do you need an array? You could just do this:
If you do need an array, understand that arrays in C# (and in .Net) are fixed-size. You would need another data structure, like a
List<String>
in order to add elements, then you can transform to an array (if truly needed) viaToArray()
.您可以简单地在 for 循环中执行此操作,如下所示,在 int 'i' 上调用 ToString
You can simply do it in a for loop as follows, calling ToString on the int 'i'
该方法将生成从“from”到“to”(包含在内)的字符串数组。
This is method that will generate array of string from 'from' to 'to' inclusive.