Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A concise way to generate an array of integers 1 to 100 in c#

Tags:

c#

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?

like image 391
Lill Lansey Avatar asked Mar 23 '12 15:03

Lill Lansey


2 Answers

Using Enumerable.Range:

Enumerable.Range(1, 100).ToArray();
like image 139
Oded Avatar answered Oct 20 '22 00:10

Oded


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.

like image 25
Andras Zoltan Avatar answered Oct 19 '22 23:10

Andras Zoltan