VSP
VSP

Reputation: 2393

c# Leaner way of initializing int array

Having the following code is there a leaner way of initializing the array from 1 to the number especified by a variable?

int nums=5;
int[] array= new int[nums];

for(int i=0;i<num;i++)
{
   array[i] = i;
}

Maybe with linq or some array.function?

Upvotes: 4

Views: 987

Answers (4)

Shai Cohen
Shai Cohen

Reputation: 6249

Maybe I'm missing something here, but here is the best way I know of:

int[] data = new int [] { 383, 484, 392, 975, 321 };

from MSDN

even simpler:

int[] data = { 383, 484, 392, 975, 321 };

Upvotes: 0

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98740

Use Enumerable.Range() method instead of. Don't forget to add System.Linq namespace. But this could spend little bit high memory. You can use like;

int[] array = Enumerable.Range(0, nums).ToArray();

Generates a sequence of integral numbers within a specified range.

Upvotes: 1

Steve
Steve

Reputation: 216253

Using Enumerable.Range

int[] array = Enumerable.Range(0, nums).ToArray();

Upvotes: 0

Lee
Lee

Reputation: 144126

int[] array = Enumerable.Range(0, nums).ToArray();

Upvotes: 6

Related Questions