Concise way to create an array of integers from 1 to 100 in C #

I'm looking for a concise way to create an array of integers from 1 to 100 in C #, i.e.

        int[] values =  {1,2,3 ..., 100}; 


so that I can use the array in the foreach loop:

       foreach (var i in values)
            // do whatever  


Any ideas?


source to share

2 answers

Usage Enumerable.Range


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




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);


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()




All Articles