Concise way to create an array of integers from 1 to 100 in C #
It probably doesn't make much sense to me that this is - Oded 18 votes (including my own +1) pretty much everyone says, but just to point out that if you're going to use integers in an array, produce anything - let's say an object , - then you can roll it all.
So let's say you want the lines:
var strings = Enumerable.Range(1,100)
.Select(i => i.ToString()).ToArray();
Will give you an array of strings.
Or perhaps MyWidget
created by calling a method that uses the index for something:
var myWidgets = Enumerable.Range(1,100)
.Select(i => ProduceMyWidget(i)).ToArray();
If the source code of the code foreach
consisted of several lines of code, then you simply use the 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 often illustrates how the traditional foreach
one can be replaced with a Select
plus call ToArray()
.
source to share