I am looking for a concise way to generate an array of integers 1 to 100 in c# , ie
int[] values = {1,2,3 ..., 100};
so that I can use the array in a foreach loop:
foreach (var i in values)
{
// do whatever
}
Any ideas?
Using Enumerable.Range
:
Enumerable.Range(1, 100).ToArray();
There's probably not much point in me putting this - Oded's 18 votes (including my own +1) pretty much say it all, but just to point out that if you're then going to use the integers in the array, to produce something - let's say an object - then you can roll the whole thing up.
So, let's say you want some strings:
var strings = Enumerable.Range(1,100)
.Select(i => i.ToString()).ToArray();
Gives you an array of strings.
Or perhaps a MyWidget
that's produced from a method call, which uses the index for something:
var myWidgets = Enumerable.Range(1,100)
.Select(i => ProduceMyWidget(i)).ToArray();
If the original foreach
code block was more than one line of code - then you just use a {}
block
var myWidgets = Enumerable.Range(1,100)
.Select(i => {
if(i == 57)
return ProduceSpecial57Widget(i);
else
ProduceByWidget(i);
}).ToArray();
Obviously this last example is a bit silly - but it illustrates often how a traditional foreach
can be replaced with a Select
plus ToArray()
call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With