Jay Sun
Jay Sun

Reputation: 1601

LINQ to create int array of sequential numbers

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?

Upvotes: 14

Views: 9900

Answers (3)

Digbyswift
Digbyswift

Reputation: 10400

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

Upvotes: 18

acoffman
acoffman

Reputation: 708

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

Upvotes: 4

Ani
Ani

Reputation: 113402

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].

Upvotes: 17

Related Questions