Lill Lansey
Lill Lansey

Reputation: 4915

A concise way to generate an array of integers 1 to 100 in 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?

Upvotes: 6

Views: 3839

Answers (2)

Andras Zoltan
Andras Zoltan

Reputation: 42363

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.

Upvotes: 6

Oded
Oded

Reputation: 499152

Using Enumerable.Range:

Enumerable.Range(1, 100).ToArray();

Upvotes: 26

Related Questions