Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to create int array of sequential numbers

Tags:

asp.net

linq

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?

like image 709
Jay Sun Avatar asked Jan 23 '12 20:01

Jay Sun


People also ask

How to make array of numbers in c#?

Create an Array Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. To declare an array, define the variable type with square brackets: string[] cars; We have now declared a variable that holds an array of strings.

Can you use LINQ on an array?

LINQ allows us to write query against all data whether it comes from array, database, XML etc.

What is Enumerable range?

Range overview. It takes two arguments. First argument is the first number in sequence (e.g. 10, means that the first number in sequence is 10). Second argument is the number of items in sequence (e.g. 11 means that it will return 11 numbers).


2 Answers

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

like image 66
Digbyswift Avatar answered Oct 19 '22 21:10

Digbyswift


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

like image 20
Ani Avatar answered Oct 19 '22 19:10

Ani