Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ways in .NET to get an array of int from 0 to n

Tags:

arrays

c#

.net

I'm searching the way(s) to fill an array with numbers from 0 to a random. For example, from 0 to 12 or 1999, etc.

Of course, there is a for-loop:

var arr = int[n];
for(int i = 0; i < n; i++)
{
  arr[i] = i;
}

And I can make this method been an extension for Array class. But is there some more interesting ways?

like image 1000
abatishchev Avatar asked May 12 '09 19:05

abatishchev


People also ask

How do you create an array of numbers from 1 to N?

To create an array of a certain range we can use the range() function as it specifies the range of the list and then typecast the range() by using the list command as shown in the code below. We can set the range of the list from 1 to N and N should be any integer number.

How do you make an array of size n?

Given a number N, the task is to create an array arr[] of size N, where the value of the element at every index i is filled according to the following rules: arr[i] = ((i – 1) – k), where k is the index of arr[i – 1] that has appeared second most recently.

How do I get the size of an array in C#?

To find the length of an array, use the Array. Length() method.


1 Answers

This already exists(returns IEnumerable, but that is easy enough to change if you need):

arr = Enumerable.Range(0, n);
like image 195
Chris Shaffer Avatar answered Oct 18 '22 04:10

Chris Shaffer