13

So instead of writing a looping function where you instantiate an array and then set each index value as the index, is there a way to do this in LINQ?

Jay Sun
  • 1,583
  • 3
  • 25
  • 33
  • Possible duplicate of [How to create array with sequence of integers in C#?](http://stackoverflow.com/questions/4588787/how-to-create-array-with-sequence-of-integers-in-c) – Michael Freidgeim Aug 04 '16 at 01:57

3 Answers3

17

You can use the System.Linq.Enumerable.Range method for this purpose.

Generates a sequence of integral numbers within a specified range.

For example:

var zeroToNineArray = Enumerable.Range(0, 10).ToArray();

will create an array of sequential integers with values in the inclusive range [0, 9].

Ani
  • 111,048
  • 26
  • 262
  • 307
17

Enumerable.Range(0, 10) will give you an IEnumerable<int> containing zero to 9.

Digbyswift
  • 10,310
  • 4
  • 38
  • 66
4

You might want to look at Enumberable.Range

For Each( var i in Enumberable.Range(1,5).ToArray()){
    Console.WriteLine(i)
}

would print out 1,2,3,4,5

acoffman
  • 708
  • 3
  • 10